02 Aug

jquery remoteselectoptions plugin

Based on some work I did for chapter 3 of jQuery 1.3 with PHP, I’ve created a plugin to encapsulate the remote selectbox trick.

The idea of this is that in a lot of cases, there may be huge select boxes in your forms, but the selected value might not ever need to change. For example, if you have a country list, and you’re pretty sure that the user is in Ireland, then it might be pointless to have a full list of countries in there if it’s unlikely to be changed.

demo
country-select

Notice that when you click the select box, it’s populated with countries. However, the source of the page does not include those countries in the HTML. So how does it do it?

How it does it is to add a focus event to the selectbox, which populates it only when it’s actually about to be changed. In this case, the missing options are in a file named countries.html which is 9k in size. So, by using this trick, we’ve saved 9k in bandwidth. Multiply that by the amount of large selectboxes in your forms, and it could be considerable.

Look at the source of that page:

<html>
	<head>
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
		<script src="jquery.remoteselectoptions.min.js"></script>
		<script>
			$(document).ready(function(){
				$('select[name=countries]').remoteselectoptions({
					url:'countries.html'
				});
			});
		</script>
	</head>
	<body>
		<em>select a country</em>

		<select name="countries"><option value="IRL">Ireland</option></select>
	</body>
</html>

All that’s needed is to include a single option in there to indicate the default, then run .remoteselectoptions() on the selectbox, telling it what url it should grab the options from.

In case you need to do some checking on the server-side based on the current selected item, the script calls the option source with a selected GET parameter set to the current selected option’s value. You might set the url to a PHP script for example, which would build up the option list based on that selected item.

Download the source here (4.5k)

Rate it here.

2 thoughts on “jquery remoteselectoptions plugin

  1. Nice demo. I didn’t even know that there were that many countries in the world! lol

    The plugin seems very easy to use, which is always good! Will you be getting a spot at jquery.com then?

  2. I’ve already submitted it to plugins.jquery.com – one of the guys on the #jquery IRC channel suggested a better name, lateselect. Another better name would be lazyselect, as this uses what might be called a “lazy load” pattern.

Leave a Reply