-2

With jQuery higher than 1.8, repeat call of attr('selected', true); unselects what it was supposed to select

an example can be found here or below:

$(document).on("click",".edit", function(){
    $("#editor").find("select").prop('selectedIndex',0);
    $("#editor").find("#whour option[value='"+this.id+"']").attr('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="editor">
 <select id="whour" name="duration[hr]"> 
  <option value="0">——</option>
  <option value="1">1 h.</option>
  <option value="2">2 h.</option>
  <option value="3">3 h.</option>
  <option value="4">4 h.</option>
  <option value="5">5 h.</option>
  <option value="6">6 h.</option>
  <option value="7">7 h.</option>
  <option value="8">8 h.</option>
  <option value="9">9 h.</option>
  <option value="10">10 h.</option>     
 </select>
</div>
    
<button id="2" class="edit">2h</button>
<button id="3" class="edit">3h</button>
<button id="4" class="edit">4h</button>
<button id="5" class="edit">5h</button>

is there a solution to that?

Arman P.
  • 4,314
  • 2
  • 29
  • 47
  • 1
    Note that `selected` is a `prop`. Shouldn't make a difference though. – Bram Vanroy Jun 20 '16 at 21:45
  • 3
    @BramVanroy It makes a difference. Using `prop` should solve the problem. But the better alternative is: `$('#whour').val(this.id);` – Ram Jun 20 '16 at 21:48
  • @Vohuman I thought jQuery would be backwards compatible with this. – Bram Vanroy Jun 20 '16 at 21:51
  • related: http://stackoverflow.com/questions/5874652/prop-vs-attr – Kevin B Jun 20 '16 at 21:51
  • 2
    @BramVanroy no, hah. in 1.6 they made a change that was absolutely not backwards compatible, reverted it in 1.6.1, and then re-implemented it in 1.8. the current versions usage of .attr and .prop are not backwards compatible with 1.6.1 or anything older than 1.6. Or was it 1.7 that they re-implemented it? who knows. – Kevin B Jun 20 '16 at 21:52

1 Answers1

0

You need to unselect all of the options first and then you can select the desired option.

Since selected is a property, you need to use .prop() to add or remove the selected property.

$(document).on("click", ".edit", function(){
    $("#editor #whour").find("option").prop('selected', false).filter("[value='"+this.id+"']").prop('selected', true);
});
gre_gor
  • 6,669
  • 9
  • 47
  • 52