Nov25Written by:Will
11/25/2009

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:
<selectid="cboList">
<optionvalue="val1">Text1</option>
<optionvalue="val2">Text2</option>
<optionvalue="val3">Text3</option>
<optionvalue="val4">Text4</option>
<optionvalue="val5">Text5</option>
<optionvalue="val6">Text6</option>
</select>
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!
3 comment(s) so far...
Hi Will,
Here is a related function I use when dealing with select inputs. It is particularly useful when you do an inline addition via ajax and need to add the select item on the client with the id that was retreived from the server ajax call.
//ADD A SELECT OPTION AND SELECT IT function AddSelectOption(field, key, text, selected) { var html = ""; jQuery('#' + field).append(jQuery(html).attr("value", key).text(text)); }
By Mitch Labrador on
11/25/2009 |
I think some of my code got eaten by the addcomment function :), or I pasted it wrong so here is the missing piece.
before the jQuery('#' + field.... statement it should:
var html = " By Mitch Labrador on
11/25/2009 |
Yes... The current iteration of the DNN blog module likes to eat up blog comments. :)
By Will on
11/25/2009 |