on Sep 12th, 2008jQuery / Javascript autocomplete checkbox-selection with memory

Edit: Fixed a small bug that would cause it to fetch to many results on slow connections, demo6.zip

So yeah, a messy title on this post - but I couldn’t really find a good way to explain this. It’s just an example I wrote up for a mate on IRC that asked for “an auto-complete Ajax widget that allows you to check auto-completed values and keep typing, remembering the ones you already checked”.

Code here: demo6.zip
Live Demo:http://totmacher.eu/upload/client.html (three characters minimum and 400ms delay)

Since it’s a few lines of code I’m only posting the javascript-code here, for the complete example I’ll post a .zip-file instead of linking it directly. Zip it up somewhere on a PHP5+ web-server and go to client.html.

Of course it won’t auto-complete anything, this is just the javascript/client-side of things, the server.php script just returns my three names and the value you put in a json string.

$(document).ready(function(){

	last_press = (new Date()).getTime()
	char_limit = 3
	delay = 300
	counter = 0
	input = $("#input")
	list = $("#list")

	do_update = function(check) {

		// Only fire one event, ever
		if (check != last_press)
			return

		// Only update the list if "delay"-milliseconds have passed and
		// the input length is greater then or equal to "char_limit"
		if ( ((new Date()).getTime() - last_press) > delay && input.val().length >= char_limit) {

			list.find("li").each(function(i, element){
				li = $(element)

				// If the checkbox in this list item isn't checked
				if(!li.find("input").attr("checked")) {
					li.remove()
				}
			})

			$.getJSON("server.php", {"value":input.val()}, function(result){
				for each (value in result) {
					// Create a new list item
					item =  $("<li></li>")

					// The checkbox, assign a unique id to it
					checkbox = $("<input type='checkbox'></input>")
								.attr("name","selected[]")
								.attr("value", value)
								.attr("id", "checkbox_"+(++counter))

					// Label that allows us to click on the text also
					label = $("<label>"+value+"</label>")
							.attr("for", "checkbox_"+counter)

					// Append the checkbox and label to the <li>-item
					item.append(checkbox)
					item.append(label)

					// Append the <li>-item to the <ul>-list
					list.append(item)
				}
			})
		}
	}

	input.keyup(function(){
		last_press = (new Date()).getTime()
		setTimeout("do_update("+last_press+");", delay+100)
	})

})

2 Responses to “jQuery / Javascript autocomplete checkbox-selection with memory”

  1. Vladon 12 Sep 2008 at 11:56 pm

    Any way to see a demo without installing a PHP server locally?

  2. Fredrik Holmströmon 13 Sep 2008 at 12:06 am

    Live demo:
    http://swecovers.se/diverse/demo4/client.html

Trackback URI | Comments RSS

Leave a Reply