Autopostback select lists in ASP.NET MVC using jQuery

Posted by rajbk on ASP.net Weblogs See other posts from ASP.net Weblogs or by rajbk
Published on Thu, 06 May 2010 16:18:48 GMT Indexed on 2010/05/06 16:29 UTC
Read the original article Hit count: 1160

Filed under:
|
|

This tiny snippet of code show you how to have your select lists autopostback its containing form when the selected value changes.

When the DOM is fully loaded, we get all select nodes that have an attribute of “data-autopostback” with a value of “true”.

We wire up the “change” JavaScript event to all these select nodes. This event is fired as soon as the user changes their selection with the mouse. 

When the event is fired, we find the closest form tag for the select node that raised the event and submit the form.

$(document).ready(function () {
    $("select:[data-autopostback=true]").change(function () {
        $(this).closest("form").submit();
    });
});

A select tag with autopostback enabled will look like this

<select id="selCategory" name="Category" data-autopostback="true">
<option value='1'>Electronics</option>
<option value='2'>Books</option>
</select>


The reason I am using “data-" suffix in the attribute is to be HTML5 Compliant.

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no characters in the range U+0041 to U+005A (LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).

The snippet can be used with any HTML page.

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about ASP.NET