[Javascript] Changing a Combobox content

Nick Fitzsimons nick at nickfitz.co.uk
Sat Oct 28 09:10:16 CDT 2006


On 27 Oct 2006, at 20:57:33, Henrique Rennó wrote:

> Hello!
>
> I did a map over an image and every time I click on a mapped point  
> it changes the content of a combobox (select). It works fine on  
> firefox but internet explorer clears the combo's content every time  
> a mapped point is clicked. Is it a problem that can be solved?
>
> This is what I did:
>
> A function to change the combo's value:
>
> function change(newvalue)
> {
> document.form_name.select_name.value = newvalue;
> }
>

Unlike something like a text input field, a select doesn't have a  
value: it has a selected option, which provides the value. To set the  
selected item, you can do one of two things; pass the number of the  
option you want to select:

function setSelectedOption(index) {
    document.form_name.select_name.selectedIndex = index;
}

or you can scan the options array looking for the item with the  
chosen value:

function setSelectedOptionByValue(value) {
    var select = document.form_name.select_name; // getting it into a  
variable makes it faster
    for (var option = 0; option < select.options.length; option++) {
       if (select.options[option].value == value) {
          select.selectedIndex = value;
          break;
       }
    }
}

(I haven't tested any of this, but it should work :-)

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/






More information about the Javascript mailing list