5 Useful jQuery Snippets for your Website

jQuery is a popular JavaScript library which is used by many developers and applications. While using jQuery you need to write less code, writing functions is less complex and there are a lot of plugins you can use for free in your web application. Even if you code everything by yourself, you need only a few rows of code to create nice and powerful features for your website. If you’re in hurry check the jQuery demo page.

Populate select menus with jQuery and Ajax

One of the most powerful jQuery function is the Ajax Suite. This example shows how-to populate a second select menu based on the option from the first select menu.

Just in case we have this select menu with the main categories:

<form>
	<label for="category">Choose: </label>
	<select id="category" name="category">
		<option value="fruit">Fruit</option>
		<option value="grain">Grains</option>
		<option value="vegetables">Vegetables</option>
	</select>
</form>

If someone has changed the value for this select menu, we want to show the equivalent menu inside the span element with the ID “subcat”. To do this we use this jQuery snippet that makes an Ajax request to a PHP file called “getSubCat.php”. After the select menu is changed a loading image will show up (in case of slow Internet connections), the PHP script is called and the sub-select menu becomes visible.

$(document).ready(function() {
	$('#category').change(function() {
		var category = $(this).val();
		$.ajax({
			type: 'GET',
			url: 'getSubCat.php',
			data: 'cat=' + category,
			dataType: 'html',
			beforeSend: function() {
				$('#subcat').html('<img src="loader.gif" alt="loading..." />');
			},
			success: function(response) {
				$('#subcat').html(response);
			}
		});
	});
});

The PHP code we are using for the file called getSubCat.php:

 array('Apples', 'Pears', 'Cherries', 'Oranges', 'Kiwis'),
	'grain' => array('Wheat', 'Corn'),
	'vegetables' => array('Tomatoes', 'Beans', 'Peas', 'Peperoni')
);
// use a database instead, this array is only some simple demo data
if (!empty($_GET['cat'])) {
	if (array_key_exists($_GET['cat'], $data)) {
		echo '
<select id="subselect" name="'.$_GET['cat'].'">';
		foreach ($data[$_GET['cat']] as $key => $val) {
			echo '
<option value="'.$key.'">'.$val.'</option>
 
';
		}
		echo '
	</select>
 
';
	} else {
		echo 'Array-key doesn\'t exist';
	}
} else {
	echo 'Invalid request';
}
?&gt;

This is a simple example on how you can use the Ajax function, the function has much more features which makes it a very flexible function.

Disable/enable the form submit button with jQuery

On pages with a registration or contact form, you like to treat the visitor to accept some terms of service before he/she can continue the form. A very nice function to do this is, to disable the submit button until the visitor has clicked some check box (like: Click here to accept the TOS). The following snippet will enable/disable the submit button after the check box is checked or not.

$('#accept').click(function() {
	if ($('#buybtn').is(':disabled')) {
    	$('#buybtn').removeAttr('disabled');
    } else {
    	$('#buybtn').attr('disabled', 'disabled');
    }
});

Together with this function, we use the following HTML for the submit button:

<input id="accept" name="accept" type="checkbox" value="y" /> I accept the conditions!
<input id="buybtn" disabled="disabled" name="Submit" type="submit" value="Send" />

Simple photo gallery with thumbnails

If you’re looking for a light-weight photo gallery function, this snippet is for you. The function works very simple: If the visitor has clicked a thumbnail the value from “href” attribute is passed to the “src” attribute from the bigger image. Thats all, check the jQuery code and of course the HTML example.

$("#thumbs a").click( function() {
	var changeSrc = $(this).attr("href");
	$("#detail").attr("src", changeSrc);
	return false;
});
<img id="detail" src="img/1.jpg" alt="big view" />
 
	<a href="img/1.jpg"><img src="thumbs/1.jpg" alt="thumb 1" /></a>
	<a href="img/2.jpg"><img src="thumbs/2.jpg" alt="thumb 2" /></a>
	<a href="img/3.jpg"><img src="thumbs/3.jpg" alt="thumb 3" /></a>

Show and hide HTML elements based on Radio selection

jQuery has great functions which show or hide HTML elements. This example is about to show some additional list based on a selection which is made by checking a radio button. The script checks first if “the” button is checked and shows the additional container, otherwise it hides the “this” container.

$('#payments input[type=radio]').click(function() {
	if ($('input[name=payment]:checked').val() == "creditcard") {
		$("#cards").show();
	} else {
		$("#cards").hide();
	}
});

The HTML snippet has a radio group and a DIV container which becomes visible when the radio with the value “creditcard” is checked.

<ul id="payments">
	<li>
<input id="creditcard" name="payment" type="radio" value="creditcard" /> Creditcard
<div id="cards">
			<label for="cctype">Choose one: </label>
<select id="cctype" name="cctype">
<option>...</option>
<option value="master">MasterCard</option>
<option value="visa">Visa</option>
<option value="amex">American Express</option>
</select></div></li>
	<li>
<input name="payment" type="radio" value="paypal" /> PayPal</li>
	<li>
<input name="payment" type="radio" value="wire" /> Wire/transfer</li>
</ul>

Count clicks for Google Analytics using jQuery

The last snippet is an easy way to count clicks from external links within a DIV container. Without the requirement to add additional Google Analytics code to your link elements, it’s possible to count those link clicks in Google Analytics.

$('#mylinks a[href^="http"]').click(function(){
 	pageTracker._trackPageview('/outgoing/'+ $(this).attr('href'));
});

This tiny function will count the links from a DIV container with the ID “mylinks” like:

	<a href="http://simpay.org/">PayPal Payments</a> | <a href="http://www.finalwebsites.com/web_hosting_promotion.php">Wordpress Hosting</a>

You can try all these function on this jQuery demo page, a download link is available on the same page. If you have any question or suggestions, please be my guest and use the comment form below.

Comments

  1. Useful snippets, thanks for sharing :-)

  2. Thanks for all this is great information. I was wondering. Is there a way to do this using PHP?

  3. Nice! Your link to download code id broken.

  4. Thanks for the info, the download link is fixed!

  5. Hello Sean,

    yes sure you can do this, but you will loose the great user experience. If you do this using PHP code you need to send each request to the web server and at the same time the page gets a refresh too ;)

  6. These are really useful snippets for websites.

    Thank you very much.

  7. Thanks for this. I’ve been wanting to get into jquery (even bought a huge book and everything!), but just haven’t had the time to experiment.

    Seems like jquery can bring alot of simplicity to web design / development.

    Do you have an samples here with jquery layouts, particularly table layouts?

    Thank… John

  8. Hello John,

    jQuery is the client side technology we need these days :)
    I found this plugin a few days ago: Table Sorter 2.0
    Is this what you’re looking for? Search also Google there are so many cool sites offering jQuery tutorials.

  9. This is a very nice collection of jQuery scripts. They are all very useful and I will be trying the “Simple photo gallery with thumbnails”. I use a similar script, but yours is much more light weight!

    Thanks much for the post!

Because of all the spam attemps I've decided to close the comment form at this time. If you have have any questions or comments please post them by using Google+ or Twitter (the links to my profiles are located at the top of this page).