Hilight an item in a droplist box

M

Mark

Hi - if I have a string, "wine", how do I search through a droplist box,
and automatically select the item that has "wine" as the text (nb. the
value field will not be the same as the text)?

eg:

ChooseOne
Food
SoftDrink
Wine
Cheese

I want to get my javascript to hilite Wine.

Thanks, Mark
 
L

Lasse Reichstein Nielsen

Mark said:
Hi - if I have a string, "wine", how do I search through a droplist box,
and automatically select the item that has "wine" as the text (nb. the
value field will not be the same as the text)?

The dropdown box is probably a select element, so by "highlight" I
guess you mean to select the option.

The following function selects all options with the correct text. If
there is more than one option with the same text, and the select
doesn't allow multiple selected options, then only the last one will
end up selected.

---
function selectByText(selectRef,text) {
var opts = selectRef.options;
for (var i=0; i < opts.length; i++) {
if (opts.text == text) {
opts.selected = true;
}
}
}
---

In your case, you will, e.g., call that functions as
selectByText(document.forms['myForm'].elements['myFoodSelect'],"Wine");

/L
 
J

jon

Mark said:
Hi - if I have a string, "wine", how do I search through a droplist box,
and automatically select the item that has "wine" as the text (nb. the
value field will not be the same as the text)?


You can use the "text" property of the option object instead of the
value. That will access the text in between the option tags. Something
like this...

function highlightSelect(word) {
for (i=0; i<document.myform.myselect.length; i++) {
if (document.myform.myselect.options.text==word) {
document.myform.myselect.selectedIndex=i;
break;
}
}
}

I'm not exactly sure what the browser compatibility for that is, but
I've been using it for a while with no problems.

best,

jon

http://www.gurupika.com/
http://forums.gurupika.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top