Archive

Archive for the ‘jQuery’ Category

Using ui autocomplete as a dropdown, with type in

April 1st, 2010 ^Lestat 1 comment

I had been using an autocomplete plugin by bassistance. 2 months later jQuery UI added autocomplete to their list of widgets. Like many plugins out there I was unable to find an autocomplete that was easy to use for my purposes. The closest I recently came to was the sexy combo plugin. I cant remember why but it was just a tad short of what I wanted to do, and I’m still quite a javascript novice.

I came up with a way to use the jQuery UI autocomplete widget as a <select> that you could also type in something if the choices in the dropdown didn’t fit your needs.

ui-autocomplete-dropdown

This example uses a local data source, but you can come up with creative ways to use remote JSON sources if you like.

<script type="text/javascript">
	$(document).ready(function() {

		// dropdown/ auto suggest
		$(".ui_dropdown").autocomplete({
			minLength: 0,
			delay: 0
		});

		$(".ui_dropdown").click(function(){

			var input = $(this);
			var inputID = input.attr('id');

			// close if already visible
			if (input.autocomplete("widget").is(":visible")) {
				input.autocomplete("close");
				return false;
			}

			// set source(s)
			var myData = '';
			if(inputID == 'input1'){
				myData = ["foo","bar","hello","world"];
			} else {
				myData = ["1","2","3","4"];
			}

			// load source
			input.autocomplete({
				source: myData
			});

			// fire search event
			input.autocomplete("search", "");
			input.focus();
			return false;
		});		

	});
</script>

In this script I am using the input id’s to define the data source.

Categories: Programming, jQuery Tags: