jQuery in practice

The most common tasks performed with jQuery include click events, gathering information, validation, and manipulating the interface.

Information gathering from common elements as well as common physical manipulation can be performed with simple jQuery. Review examples below.

Retrieve a value from a textbox:

$('#<%=YourTextbx.ClientID%>').val();

Establish a value for a textbox:

$('#<%=YourTextbx.ClientID%>').val("ValueHere");

Retrieve a value from a dropdown:

$('#<%=YourDropdnList.ClientID%>').val();

Set a checkbox as checked:

$('#<%=YourCheckbx.ClientID%>').prop('checked',true);

The Microsoft AJAX library provides support for jQuery validation. Many consider jQuery cleaner and more simple validation. Review this code example for determining if textboxes are empty:

$(document).ready(function() {
	$('#Submitbutton').click(function(e) {
		var isValid = true;
		$('input[type="text"]').each(function() {
			if ($.trim($(this).val()) == '') {
				isValid = false;
				$(this).css({
					"border": "4px ridge red",
					"background": "#AE6776"
				});
			}
			else {
				$(this).css({
					"border": "2px solid green",
					"background": "#736F6E"
				});
			}
		});
		if (isValid == false)
			e.preventDefault();
		else
			alert('Thank you for submitting');
	});
});

This code example only permits numeric values in a textbox:

$(document).ready(function(){
	$('#<%=NumOnlyTxbx.ClientID%>').keydown(function(e)
	{
		if (e.shiftKey)
			e.preventDefault();
		else
		{
			var nKeyCode = e.keyCode;
			//Tab or Backspace dismissed
			if (nKeyCode == 8 || nKeyCode == 9)
				return;
			if (nKeyCode < 95)
			{
				if (nKeyCode < 48 || nKeyCode > 57)
					e.preventDefault();
			}
			else
			{
				if (nKeyCode < 96 || nKeyCode > 105)
				e.preventDefault();
			}
		}
	});
});

This example ensures a submitted end date is greater than the start date:

$(document).ready(function(){
	$("#TextDate").datepicker({
		numberOfMonths: 2,
		onSelect: function(selected) {
			$("#DateFromText").datepicker("option","minDate", selected)
		}
	});
	$("#DateFromText").datepicker({
		numberOfMonths: 2,
		onSelect: function(selected) {
			$("#TextDate").datepicker("option","maxDate", selected)
		}
	});
});