views:

34

answers:

2

Basically this, but in pure javascript: http://stackoverflow.com/questions/2346257/how-to-get-value-of-select-tag-based-on-content-of-select-tag-using-nokogiri

So I have a select list with a lot of countries/states, and I want to be able to select one based on what is between the <option> tags.

<option value="4783">Argentina</option>

(I know i could use the value, but each one is a random mesh of numbers, so i would have to collect each individual one - not economical...)

+1  A: 

It is a bit painful, but in pure JavaScript:

for(var i=0,sL=mySelObj.length;i<sL;i++){
  if(mySelObj.options[i].text == myValue){
    mySelObj.selectedIndex = i;
    break;
  }
}
scunliffe
Thanks! Works a charm!!
Zac Altman
no problem, glad to help!
scunliffe
How is that painful?
Tim Down
painful in that you need to iterate over the list... meaning that if the desired value is the last item and there are 100's of items you have to check each before selecting the final option. Where possible I would always try and pre-select the value at the server where "hopefully" determining the selected option at code generation time is easier.
scunliffe
Oh, I see. I thought you meant painful in comparison to other client-side solutions.
Tim Down
A: 

The textContent property lets you see what's inside the tag. Off my head and without testing, that should work:

function selectByDisplayValue(selectTag, displayValue)
{
    var options = selectTag.getElementsByTagName('option');
    for(var i = 0; i < options.length; i++)
        if(options[i].textContent == displayValue)
        {
            options[i].selected = true;
            break;
        }
}

Where selectTag is the DOM object of your <select> tag, and displayValue is the display value of the option you want to select (for your example, "Argentina" it would be).

zneak
`textContent` is a DOM Level 3 method that is not supported by IE (and some other minor or older browsers). For `Option` objects you can use `.text`, which goes way back to JavaScript 1.0.
bobince