jQuery - Change the Default Option in a Select Listbox
Jan
28
Written by:
1/28/2009
If you haven't already heard all of the hub-bub about jQuery, it is quite simple. jQuery is an open source JavaScript library. It's main purpose is to make your JavaScript development easier, and faster. Oh BOY does it!!! We have been using it on our production sites for about 2 weeks now.
First Day Using jQuery
Today, I had to change the default selection of a SELECT listbox on the client-side, after page load in a DotNetNuke module. jQuery was the obvious candidate to make this happen. Especially since I've done this before using JavaScript, and I know how much code it can take to make it happen reliably and on all major web browsers.
I set out to make this happen. However, I fell into a learning curve that I didn't expect to hit. It reminded me of when I was trying to first learn VB.Net, and I was thinking of binding data recordset-style instead of the prescribed (at the time) dataset style. I was just thinking in the wrong way. I had to adapt and understand how I was supposed to use the API.
After a full day of using jQuery, I cannot believe how powerful using jQuery can be.
Changing the Default Select Listbox Option
I had a form that had an HTML listbox on the page. It rendered, selecting a default value that I was asked to change to another value. This is an ideal test case. Let's say that we have the following SELECT element on a web page.
<select id="cboDays" name="cboDays">
<option value="Sunday" selected="selected">Sunday</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
</select>
The default selected value is the Sunday OPTION. For our example, let's say that we need for the default value on page load to be Wednesday instead.
We could do this via our typical JavaScript methods, but that is a lot of work. Let's instead use jQuery. First of all, you need to download the jQuery script library and include it on your website/page.
Now I am going to hit you with a huge eye opener. Here is the jQuery script that will solve our problem:
jQuery("select#cboDays option[selected]").removeAttr("selected");
jQuery("select#cboDays option[value='Wednesday']").attr("selected", "selected");
Could it be??? Only two lines of JavaScrip code??? Yes. It works. I could go into very great detail about all of the ins and outs of selectors, but the jQuery documentation already does a great job of it for me.
Basically, the first portion, jQuery(string) is the selector. Selectors always return a collection of Object. Something I LOVE about jQuery is its CSS-style of selecting HTML elements on the page. This makes it incredibly easy to find and manage HTML elements if you've had any experience using CSS at all.
In the first line of code, all OPTION children of the SELECT element with the ID of "cboDays" are selected. In our case, there is only one element. The second method call seeks to remove any SELECTED attributes in the OPTION tag.
The next line of code uses a similar selector, but only returns a single object matching the OPTION child of the same SELECT element. The OPTION element we selected was the one with the attribute, VALUE, having the value of "Wednesday."
Sounds simple enough, right? I am geeking out over this!
I hope that this blog entry gives you a little more confidence to write your own jQuery scripts, or answers a question you've had.
Technorati Tags:
DNN, DotNetNuke, DNN Blog, jQuery
Copyright ©2009 Will Strohl
20 comment(s) so far...
Re: jQuery - Change the Default Option in a Select Listbox
Perfect!! Hard to find those lines
By Andrew on
3/26/2009
|
Re: jQuery - Change the Default Option in a Select Listbox
I've used this with success in the past. However, I've changed things to where I have a need to iterate through dropdown elements with a specific class. So to do so I utilize the following:
$('select[class=facState]').each(function() { // Code here });
But I'm unable to figure out how to reference the option[selected] attribute of each of the matching dropdowns returned by the each method. Might you be able to help?
Thanks
By Impress TheNet on
10/1/2009
|
Re: jQuery - Change the Default Option in a Select Listbox
I think you should be able to use a variation of:
jQuery('option:selected')
But that depends on your rendered mark-up.
By Will on
10/1/2009
|
Re: jQuery - Change the Default Option in a Select Listbox
there's some way of setting the default value by using the text of the select list instead of the value?
By eds on
11/25/2009
|
Re: jQuery - Change the Default Option in a Select Listbox
That's easy! :D I just blogged about this...
How to Change the Default Listbox Option Using jQuery
By Will on
11/25/2009
|
Re: jQuery - Change the Default Option in a Select Listbox
Many thanks for this solution. The logic seems so simple.
By Kyle Welsby on
12/2/2009
|
Re: jQuery - Change the Default Option in a Select Listbox
Awesome! Exactly what I was looking for!
By Dave on
2/10/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
I use your example to set a new default value in a lookup field in a sharepoint list. I have added a list (Report) as a lookup field to the image library function.
On image upload the user must fill in image info before saving (these are all standard features). Additionally, I want the 'Report' lookup field to be set to the latest added report. I successfully get the Id of this report through the "SPServices.SPGetLastItemId" function and save it as "var lastId".
My problem is that after that, nothing happens. I think it has something to do with the id of the select tag. In aspx the id looks like this:
Using the rendered select id, I based my functions on your example. This is my code:
$('select#ctl00_m_g_d6e8be2f_9d11_4698_9a17_5b0db8e4866e_ff2_1_ctl00_Lookup option:selected').removeAttr('selected'); $('select#ctl00_m_g_d6e8be2f_9d11_4698_9a17_5b0db8e4866e_ff2_1_ctl00_Lookup option[value=lastId]').attr('selected', 'selected');
None of the jQueries are doing anything. The "wrong" default is still selected, and the option with my id (=lastId) is not selected.
What am I doing wrong?
By Marcus on
5/17/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
@Marcus: Unfortunately, your code didn't come through, for obvious security reasons. Can you please email me at "will.strohl" using the gmail domain?
By Will on
5/17/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
@Will: I sent you an email on the 17th. I hope it didn´t land in your junk mail due to securtity issues because of the scripts in it.
I´m thankful for your help!
By Marcus on
5/21/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
@Marcus: Actually, I had trouble getting to it due to time. I answered it yesterday though.
By Will on
5/21/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
thanks u r a life saver...
most websites say u all u have to do to change the value of a select is simply do this;
$("#select_obj").val('1');
which does NOT work!
By Eric on
9/13/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
@Eric: My pleasure! :)
By Will on
9/13/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
I am ready to pull my hair just to unselect a selected value from this drop down.
var selectedReasonDetail = $('#reasonDetailList option:selected'); electedReasonDetail.attr('text') + " is the option selected"); selectedReasonDetail.removeAttr('selected'); selectedReasonDetail.attr('selected',false); electedReasonDetail.attr('text') + " is the option selected");
What am I doing wrong? :(
By CyIam on
12/9/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
@Cylam: It would be extremely difficult to tell you without additional troubleshooting information.
By Will on
12/9/2010
|
Re: jQuery - Change the Default Option in a Select Listbox
what if I want to do exactly the same, but these elements are missing: id="cboDays" name="cboDays" ? It is possible? How the things change in this case? Thank you
By pkiulian on
7/26/2011
|
Re: jQuery - Change the Default Option in a Select Listbox
@pkiulian: Yes. You just need a selector. If this is the only "select" element on the page, you can select by the SELECT tag. If this is wrapped by another HTML element, you can select based on that. For example, jQuery('#divWrapper select').
By Will on
7/26/2011
|
Re: jQuery - Change the Default Option in a Select Listbox
$("#month option[value=d.getMonth()]").attr("selected", "selected"); Not working for me.. please help
By Biswajit on
12/21/2011
|
jQuery - Change the Default Option in a Select Listbox
My question is easy, when assigning the new value to the Select Listbox why is not taking the value if I use a variable, like:
$("select#cboFees option[selected]").removeAttr("selected"); var myvar='All Users'; $("select#cboFees option[myvar=valor]").attr("selected", "selected");
It doesn't preselect. Please advise.
By Jesus on
1/10/2012
|
Re: jQuery - Change the Default Option in a Select Listbox
@Jesus: Looks like your jQuery selectors are not right.
$("select#cboFees option:selected").removeAttr("selected"); var myvar='All Users'; $("select#cboFees option[" + myvar + "='valor']").attr("selected", "selected");
By Will on
1/10/2012
|