Continuing with my love of jQuery, today I bring you a few little snippets of code for working with select lists that have a “Please select’ entry indicating a user should select an option. Ginsu Knives

As an additional added bonus (this is one of those “but wait, there’s more” moments) I will throw in some jQuery validation to indicate the user must select if they haven’t.

But wait, there’s more! Not only that, for the same low price you get the “Please select” option removed once the user has selected an option.

Sound to good to be true? Well it’s not.

So what are the ingredients we need for this recipe:



  1. Get yourself the latest version of jQuery over here
  2. Get yourself this great jQuery validation plugin over here
  3. 1 medium-large brain

Ok lets get started but first lets set the scene. The screenshot below shows a project I am currently working on with the validation activated:

image

As you can see the yellow icons indicate that some data has not been supplied, including the 4 dropdown list boxes with the ‘Please select’ option.

jQuery Validation

This plugin is remarkably simple to use, even replacing the traditional asp.net validation if you want,which I do. Not that I dislike asp.net validation, this is just cleaner.

So to implement it we add the following:

$("#main").validate();

Yes that’s it! #main is my form that I would like to validate. Since my form is contained in an asp.net masterpage I only ever need to call this line once.

Now in my case I have extended it slightly to allow it to play nicely with asp.net, so to get the effect shown in the screenshot I have added the following code:

$("#main").validate({ onsubmit: false, invalidHandler: function (form, validator) { var errors = validator.numberOfInvalids(); if (errors) { var message = errors == 1 ? 'Woops! You have 1 invalid field. It has been highlighted' : 'Woops! You have ' + errors + ' invalid fields. They have been highlighted'; $("div.error span").html(message); $("div.error").show(); } else { $("div.error").hide(); } } }); $(".button-validate").click(function (evt) { var isValid = $("#main").valid(); if (!isValid) { evt.preventDefault(); } });

The invalidHandler code adds the summary in red at the top of the screenshot and the click event handler on classes of type .button-validate triggers the validation on the form. Note that this is a set once, run everywhere validation as long as I follow the pattern of styling my buttons with the class .button-validate.

Ok now that we have our validation code in place we need to make it useful. Check out the markup shown below:

<fieldset><legend>Organiser Detailslegend><hr/><labelfor="txtFirst">Firstlabel><asp:TextBoxID="txtFirst"runat="server"CssClass="text-field required"ToolTip=" ">asp:TextBox><labelfor="txtLast"class="second-column">Lastlabel><asp:TextBoxID="txtLast"runat="server"CssClass="text-field required"ToolTip=" ">asp:TextBox><br/><hr/><labelfor="txtPosition">Positionlabel><asp:TextBoxID="txtPosition"runat="server"CssClass="text-field required"ToolTip=" ">asp:TextBox><br/><hr/><labelfor="txtEmail">Emaillabel><asp:TextBoxID="txtEmail"runat="server"CssClass="text-field required email"ToolTip=" ">asp:TextBox><br/><hr/><labelfor="txtPhone">Phonelabel><asp:TextBoxID="txtPhone"runat="server"CssClass="text-field required"ToolTip=" ">asp:TextBox><br/><hr/><labelfor="txtOrganisation">Organisationlabel><asp:TextBoxID="txtOrganisation"runat="server"CssClass="text-field required"ToolTip=" ">asp:TextBox><br/><hr/><labelfor="txtDepartment">Departmentlabel><asp:TextBoxID="txtDepartment"runat="server"CssClass="text-field required"ToolTip=" ">asp:TextBox><hr/><br/><br/><hr/><labelfor="cboIndustry">Industrylabel><asp:DropDownListID="cboIndustry"runat="server"class="required"ToolTip=" "/><labelfor="cboSector"class="second-column">Sectorlabel><asp:DropDownListID="cboSector"runat="server"class="required"ToolTip=" "/><br/><hr/><labelfor="cboSize">Sizelabel><asp:DropDownListID="cboSize"runat="server"class="required"ToolTip=" "/><labelfor="cboCountry"class="second-column">Countrylabel><asp:DropDownListID="cboCountry"runat="server"class="required"ToolTip=" "/><hr/><br/>fieldset>

Hopefully you will be appreciating how clean the mark up is Smile Not an ounce of styling in site. It all sits in the CSS where it belongs

Anyway, to get the validation to work we just need to add the class ‘required’ to any elements that must be entered and override the default message that would be displayed by entering a single empty character in the ToolTip (title if not asp.net control). That’s it, now our jQuery validation knows what to validate.

In case you are interested, when the validation fires it inserts a label in to the page with a class of ‘error’. This is what I am using to display the little yellow warning icon. I am styling the label with the little snippet below:

label.error { background-position: left top; background-image: url('../img/yellow-icons.png'); background-repeat: no-repeat; background-position: -18px -146px; width: 12px; height: 12px; }

jQuery UI

Oh, in case your wondering where the little yellow icon comes from (not that it is mind blowingly amazing) this is all part of the jQuery UI package I am using on the site.

When rolling your own theme using the Theme Roller (you can find it here) you also get this lovely sprite of icons to use. Nice Smile

yellow-icons

jQuery – remove that pesky ‘Please select’

Ok the final steak knife in our set of Ginsu knives is the jQuery code to remove the ‘Please select’ option from the list.

In this instance the dropdown list uses the asp.net databinding to populate itself.

list.DataTextField = "Industry"; list.DataValueField = "IndustryID"; list.DataSource = engine.GetLookupIndustry(); list.DataBind();

The ‘Please select’ option is added after the list is populated by inserting a new item at the Zeroth (is that a word) position with a value of string.empty.

if (addDefaultSelect) { list.Items.Insert(0, new ListItem("Please select", string.Empty)); }

So we now have our option we just need to remove it on the client side when the user actually selects a valid option.

And to do that we of course use a little snippet of jQuery:

$("option").click(function () { var defaultOption = $(this).parent().find("option[value='']"); if (defaultOption != null && $(this).attr("value") != '') { defaultOption.remove(); } });

This is loaded in my page load js file which again is part of my asp.net MasterPage so I only every need to call this once for the entire site as long as I follow the pattern.

Simple, neat and elegant, if I do say so myself.

BondiGeek