Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

get index of item in listbox

Status
Not open for further replies.

TheInsider

Programmer
Jul 17, 2000
796
CA
Hello,
Is there a built-in method [that works in both IE and Netscape] to get the index of an item in a combo/listbox based on its value or text, other than using a for-loop?

In my onSubmit event I validate some user input, based on some criteria I may need to automatically select a certain option in a combo box. I am currently using a for-loop, but I don't want to re-invent the wheel. I know that I could use the following to do the selection:
Code:
combobox.selectedIndex = [desired index]
However, the combo box data is loaded from a table and if records are added or subtracted from the table, the index will change.

Thanks,
TheInsider
 
no core js method to get selectedIndex by text or value...you'll have to stick with the loop.




=========================================================
if (!succeed) try();
-jeff
 
Thanks for the reply. I'm actually trying to set the index by value/text... but in any case, I think you are right. The MSDN help files list the functions selectByValue and selectByText... but javascript doesn't seem to acknowledge these.

Here's Microsoft's example:
Code:
function thisPage_onenter()
{
   ListBox1.addItem("Cars", 1);
   ListBox1.addItem("Planes", 2);
   ListBox1.addItem("Trains", 3);
   ListBox1.selectByValue(1);
}

didn't work for me though...
 
you can make your own though:
[tt]
<script language=&quot;javascript&quot;>
function selectByValue(oSel,sVal) {
for (x = 0; x < oSel.options.length; x++)
if (oSel.options[x].value == sVal) {
oSel.options[x].selected = true;
return true;
}
}
</script>

<body onload=&quot;selectByValue(document.forms[0].sel,'3');&quot;>
<form>
<select name=&quot;sel&quot;>
<option value=&quot;1&quot;>one</option>
<option value=&quot;2&quot;>two</option>
<option value=&quot;3&quot;>three</option>
</select>
</form>
</body>

[/tt]
=========================================================
if (!succeed) try();
-jeff
 
Thanks for the reply. That is the function that I am currently using. I just wanted to know if I was re-writing a function that is already supplied by javascript. Apparently not.
Thanks again,
TheInsider
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top