Change a select menu using jQuery
I don’t know why this is mind bending, but I seem to hit a wall every time I want to do page manipulations involving <select> boxes. Particularly, when I want to change the value selected. Based on the number of support posts I found, I’m clearly not alone.
There are two common ways to change the value selected (i.e. displayed) in a <select> menu: alter the selectedIndex or the value attribute. Which one you use depends on the information you have at hand to alter the <select>.
The selectedIndex is an incremented number assigned to each <option>. in the <select>. In other words, it has no bearing whatsoever on the value of a given option. So if you know the order of the <option>’s in your <select> and can choose based on that, you can do this…
<!-- CHANGE A SELECT BASED ON INDEX -->
<input id="change_value" name="change_value" type="button" value="Change Menu" />
<select id="my_select_box" name="var_name">
<option selected="selected" value="aaa">Some value</option> <!-- index value of 0 -->
<option value="bbb">Some other value</option> <!-- index value of 1 -->
</select>
<script type="text/javascript">
$(function() {
$('#change_value').click(function(){
$('#my_select_box').attr('selectedIndex', 1);
alert($('#my_select_box option:selected').text());
});
});
</script>Alternatively, you can change a <select> to match the value attribute of an <option>. This is probably a more common scenario..
<!-- CHANGE A SELECT BASED ON OPTION VALUE -->
<input id="change_value" name="change_value" type="button" value="Change Menu" />
<select id="my_select_box" name="var_name">
<option selected="selected" value="aaa">Some value</option> <!-- index value of 0 -->
<option value="bbb">Some other value</option> <!-- index value of 1 -->
</select>
<script type="text/javascript">
$(function() {
$('#change_value').click(function(){
$('#my_select_box').val('bbb');
alert($('#my_select_box option:selected').text());
});
});
</script>Hope that helps, it’s as much for you as it is me.




Data security without software or hardware