This content is a little crusty, having been with me through 3 separate
platform changes. Formatting may be rough, and I am slightly less
stupid today than when I wrote it.
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 `
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
menu: alter the
selectedIndexor the
valueattribute. Which one you use depends on the information you have at hand to alter the
. The
selectedIndexis an incremented number assigned to each
`. in the `
. In other words, **it has no bearing whatsoever on the value of a given option.** So if you know the **order** of the
`'s in your `
` and can choose based on that, you can do this…
Some value
Some other value
Alternatively, you can change a `
<select >` to match the `value` attribute of an `
<option >`. This is probably a more common scenario..
<pre lang="html" >
<!-- 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. :-)
Please enable JavaScript to view the
comments powered by