The Mighty Blog

Nov25

Written by:Will
11/25/2009  RssIcon

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!

Technorati Tags: ,,

3 comment(s) so far...


Gravatar

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
Gravatar

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 = "if (selected == true) html += " selected = 'selected'";

This will select the new option depending on the "selected" parameter.

By Mitch Labrador on   11/25/2009
Gravatar

Yes... The current iteration of the DNN blog module likes to eat up blog comments. :)

By Will on   11/25/2009

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 
Add to Technorati Favorites
Tweet about my blog
Will Strohl - The Mighty Blog - RSS Feed

Tag Cloud

Sort by:Tag | SizeRSS
The opinions expressed here are the personal opinions of Will Strohl and do not necessarily represent the views and opinions of the DotNetNuke Corporation.
© Copyright 2004-2010 by Will Strohl. All rights reserved.Website Skinned By: Ralph Williams  Website Hosted By: Applied Innovations