Zac Altman
Zac Altman

Reputation: 1213

Javascript: Select option based on its contents

Basically this, but in pure javascript:
How to get 'value' of select tag based on content of select tag, using Nokogiri

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)

Upvotes: 2

Views: 6354

Answers (4)

surfalot
surfalot

Reputation: 11

Just 10 years late, but let's look at a new age solution.

If you are working in ES6+ here is a simple "one liner" to do the trick.

If you require broad compatibility, use a transpiler or another solution.

let $select = document.querySelector('select[name="countries"]');
let compareValue = 'Argentina';

$select.value = [...$select.options].filter(option => {
    return option.innerText === compareValue;
})[0].value;

The true one-liner expression:

$select.value = [...$select.options].filter(option => option.innerText === compareValue)[0].value;

Upvotes: 1

Bala Clark
Bala Clark

Reputation: 1524

Now that querySelector is available in most browsers you can use:

document.querySelector('select').selectedIndex = 
    document.querySelector('option[value=4783]').index;

Upvotes: 2

zneak
zneak

Reputation: 138261

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).

Upvotes: 0

scunliffe
scunliffe

Reputation: 63686

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;
  }
}

Upvotes: 5

Related Questions