Click to See Complete Forum and Search --> : Simple One: How to set selectedindex from a value


Helj
07-18-2003, 10:10 AM
I have a pulldown like so:

<select name="sel">
<option value="1">AAA</option>
<option value="12">BBB</option>
<option value="34">CCC</option>
</select>

I know how to use frmMain.sel.selectedIndex = 1; etc, but what if I was given a string 'AAA' and wanted to select that item in the pulldown?

I'm sure its something nested like:

frmMain.sel.selectedIndex = frmMain.sel.selectedIndex(indexof('AAA')); or something along those lines, just not sure of the syntax.

Thanks!

Helj

pyro
07-18-2003, 10:20 AM
Try something like this:

<script type="text/javascript">
function setVals() {
sel = document.myform.sel;
str = "BBB";
for (i=0; i<sel.options.length; i++) {
if (sel.options[i].text == str) {
sel.selectedIndex = i;
}
}
}
</script>

</head>

<body onload="setVals();">
<form name="myform">
<select name="sel">
<option value="1">AAA</option>
<option value="12">BBB</option>
<option value="34">CCC</option>
</select>
</form>

Khalid Ali
07-18-2003, 10:22 AM
what you can do is run a loop through the list of options in a select box and match the text value with the value you are given..wherever given value is matched with the text of the option you can set the selectedIndex to that.

for(var x=0;x<...

if(givenValue==options[x].text){
listbox.selectedIndex = x;
}

Helj
07-18-2003, 10:27 AM
Thanks!