jQuery Autocomplete

Autocomplete  widget allows to search and select results from a pre-populated list and the source can be from database, array etc. Once you start typing the widget starts searching for results to matched results.

One of the issues which I find with autocomplete is that it gives the user an option to select from the list or type in anything. I have working with few projects which wants only selection from list and not any free text.

To solve this issue, we can use change event with autocomplete which will check if you have selected the value and if you have not then it will delete the value. The change event is being triggered when the value is being changed in the textbox or if the field is being blurred. After selecting the option from the list it will be a good option to disable the tying from the textbox and add a link next to the text box to inform the user to activate tying if they want to make changes. This way the textbox will be under control and typing can be prevented.

Sample Code

$(document).ready(function () {
 
 $("#category").autocomplete({
 source: function (request, response) {
 $.ajax({
 url: "http://en.wikipedia.org/w/api.php",
 dataType: "jsonp",
 data: {
 'action': "opensearch",
 'format': "json",
 'search': request.term
 },
 success: function (data) {
 response(data[1]);
 }
 });
 },
 change: function (event, ui) {
 if (ui.item == null || ui.item == undefined) {
 $("#category").val("");
 $("#category").attr("disabled", false);
 } else {
 $("#category").attr("disabled", true);
 }
 }
 });

$('#changeCategory').click(function (e) {
 e.preventDefault();
 $("#category").attr("disabled", false);
 });
});

Resources:
Reading materials link
Working fiddle link

Happy Coding

JQuery Tips #1

.wrap() vs wrapAll()

Simply wrap HTML around an element. The wrapAll() method will wrap all the elements matched into another element whereas the .wrap() method which wraps the matched elements individually. The example wraps an img tag with anchor.

$j("img#tooltip").wrap('<a href="#" id="show_tooltip"/>');

Adding a row in the middle of the table

If you want to add an additional row in between the table rows than .after() or .insertAfter() is way to do.

var newrow = $j('<tr><td colspan=2></td></tr>');
 $j('#form_840_location').after(newrow);

or

newrow.insertAfter('#form_840_location')

The only difference between the two is that .insertAfter() returns all inserted elements whereas .after() has no return value. The detailed explanation can be read from this link.

tooltip
Tooltip is a useful interface paradigm. Its use can explore the action without invoking. tooltip can be set using jquery or with css. The css example can be found here.

With jquery it can be done with .tooltip()

 $('#showtooltip').tooltip(tooltipOptions);