Crawlicious

tools for web business

jQuery: how to select an option by it’s text

| 0 comments

Supposedly you should be able to select select options by their text values like this

$(‘#myselect’).val(‘aval’);

This doesn’t seem to work if your options have value attributes however.

So, to select options by their text value, when you have values set (like this)

<select id=”myselect”><option value=”1″>alpha</option><option value=”2″>beta</option></select>

You can use a filter like this

$("#single option").filter(function() { return this.text == 'sometext'; }).attr('selected', 'selected');
 

Here is a whole example... The html was borrowed from some other place where they were explaining this, but they forgot the fact it doesn't work if you add values.
<select id="single">
    <option value="1" >Single</option>
    <option value="2" >Single2</option>
    <option value="3" >Single3</option>
    <option value="4" >Single4</option>
    <option value="5" >Single5</option>
    <option value="6" >Single6</option>
    <option value="7" >Single7</option>
    <option value="8" >Single8</option>
    <option value="9" >Single9</option>
</select>
<script>
    $("#single option")
      .filter(function() { return this.text == 'Single7'; })
      .attr('selected', 'selected');
</script>

Leave a Reply