Simple jQuery Autosubmit Plugin

One issue that I have with ASP.NET is how often it injects inline styles and scripts into your pages. One example is the “AutoPostBack” attribute that you can add to your DropDownList and RadioButtonList server controls. When this attribute is added, an inline “onchange” event handler will be added to your markup along with some other scripts. Ideally, this functionality should be handled in an external JS file, and it’s really not that hard to do.

Here’s a quick jQuery plugin that will accomplish that without having to rely on .NET’s “AutoPostBack” feature.

/// <summary>
/// The parent form of the provided element(s) will be submitted when its/their value changes.
/// </summary>
/// <param name="options.ignore">An ignore option is available (array) to prevent the form from submitting when certain values are chosen. By default, options with an empty string value are ignored.</param>
/// <param name="options.trigger">If trigger is omitted, the parent form will be submitted. Otherwise, a click event will be triggered on the provided jQuery object.</param>
(function(factory) {
	if (typeof define === 'function' && define.amd) {
		// Register as an anonymous module
		define(['jquery'], factory);
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function ($) {
	$.fn.autosubmit = function (options) {
		var settings = $.extend({
			'ignore': ['']
		}, options);

		this.change(function () {
			var $this = $(this);

			if ($.inArray($this.val(), settings.ignore) === -1) {
				if (typeof settings.trigger !== 'undefined') {
					settings.trigger.click();
				} else {
					$this.closest('form').submit();
				}
			}
		})

		return this;
	}
}));

Using the plugin is very easy. Create your DropDownList as usual, but give it a CssClass attribute so you can reference it easily:

<asp:DropDownList ID="myDropDownList" CssClass="auto-drop-down" runat="server">…</asp:DropDownList>

Include jQuery and the plugin file in your page, then write some JS similar to the following:

$('.auto-drop-down').autosubmit();

The plugin also allows you to specify certain values that will not autosubmit when chosen. For example, you may have a drop-down with a “Select an option” choice, in which case, you wouldn’t want to submit the form unless a different choice was made. Here’s how to ignore certain values:

$('.auto-drop-down').autosubmit({'ignore': ['', 'n/a', 'empty']});

One more thing to point out — be sure to include a submit button even if the autosubmit feature makes it unnecessary. If someone isn’t using JavaScript, they should still be able to use the drop-down on your page. Another line of JS for hiding the submit button is trivial:

$('#my-button').hide();

Leave a Reply

Your email address will not be published. Required fields are marked *