Reputation: 876
I am working with an application where I need to create a select then be able to change the value so that if it is reset it changes to the new value. This means changing the value on the DOM not just the value shown to the user. For example .val() doesn't work because if you reset the select box it reverts to the previous value. The way I have found to do this with other elements is with the .attr("value", ) function. The issue is that this doesn't work on a select. I also need to set the select by the value not the index of the option I am picking. I am idealing look for something that would work the same as attr does with everything else.
Upvotes: 0
Views: 675
Reputation: 780673
There's no value
attribute in a <select>
, the default value is indicated by having the selected
attribute on that option.
You can use an attribute selector to select the option by value: $("#selectID option[value='foo']")
$("#change").click(function() {
$("foo option").attr("selected", false);
$("#foo option[value='2']").attr("selected", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="foo">
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
<input type="reset"/>
</form>
<button id="change">Change default</button>
Note that this also changes the current selection, not just the default. I haven't been able to figure out a way to change just the default.
Upvotes: 2