Suman Thota Suman Thota - 5 months ago 19
jQuery Question

Changing option value with jquery not working

<select id="dd">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

//change option to 2; works
$("#dd").find('option[value=2]').attr("selected",true);
$("#dd").find('option[value=2]').attr("selected",false)

//change option to 3; works
$("#dd").find('option[value=3]').attr("selected",true);
$("#dd").find('option[value=3]').attr("selected",false);

//change option back to 2; doesn't work
$("#dd").find('option[value=2]').attr("selected",true);


Changing value to back a value that was set earlier, doesn't work..
Any idea? if I am doing something wrong...

Answer

Is this what you are trying for?

$('#set2').click(function(){
  $("#dd option[value=2]").prop("selected",true);
});

$('#set3').click(function(){
  $("#dd option[value=3]").prop("selected",true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="dd">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<button id="set2">Set to 2</button>
<button id="set3">Set to 3</button>

Comments