Will "the Mighty" Strohl

Selecting A List Option Using the Text Attribute via jQuery

Here is another blog by request.  I blogged not too long ago about using jQuery to change the default option in a listbox.  As a result, a comment was added that asked me how to change the selected option using only the text, and not the value.  Here is the answer!  Doing this is actually quite simple, but may not be straightforward at first. 

In order to demo this, we need a listbox (select, combo box, drop down list, etc.).  Here is the one I am using for my example:

<select id="cboList">
    <option value="val1">Text1</option>
    <option value="val2">Text2</option>
    <option value="val3">Text3</option>
    <option value="val4">Text4</option>
    <option value="val5">Text5</option>
    <option value="val6">Text6</option>

Just a simple drop down list, right?  Right.  Now, let’s use jQuery to select the default value that will show to your website visitors.

jQuery(document).ready(function() {
    jQuery('#cboList option:contains(\'Text5\')').attr('selected', 'selected');

Just (technically) one line of jQuery to make this happen!  Imagine doing that on your own using plain old JavaScript.  Here it is in action!

Now you can try this on your own!

Technorati Tags: ,,

blog comments powered by Disqus