Create customised auto-complete

$(document).ready(function() {

$(“#apex-owner-autocomplete”).keyup(function() {

var term = $(‘#apex-owner-autocomplete’).val();

if (term.length > 2) {

$.ajax({

//the servlet address to get json data

url: “<c:url value=”/ajax/apex-parent-name.htm”/>”,

dataType: “json”,

data: {

//parameters that need to forward with the url

name_startsWith: term,

filterName:”PARENT_NAME”

},

success: function(data) {

//remove the existing dropdown list

$(“#apex-owner-list ul li”).remove();

//map function translate all items in an array or array-like object to another array of items.

$.map(data.type, function(item) {

//add each matches to the dropdown list

var matchItem = “<input type=’checkbox’ class=’ownerManager’ name=’matchItem’ value='” + item.name + “‘>” + item.name;

$(“<li/>”).append(matchItem).prependTo(“#apex-owner-list ul”);

})

if (data.type != null) {

//if there is a match

$(‘#btnOwnerSelect’).show();

$(“#log”).show();

$(“#apex-owner-list ul”).show();

}

},

error:function(XMLHttpRequest, textStatus, errorThrown) {

alert(textStatus);

}

});

}

else {

//remove the dropdown list if the search term has less than 3 character

$(‘#apex-owner-list ul li’).remove();

}

});

$(“#btnOwnerSelect”).click(function() {

//insert selected item from autocomplet dropdown list to the log frame

$(“#apex-owner-list input:checked”).each(function() {

var selectedItem = this.value;

var isSelected = false;

$(“#log div”).each(function() {

//if selected already

if($(this).text().indexOf(selectedItem)>-1){

isSelected = true;

}

});

if(!isSelected){

$(“<div/>”).append(selectedItem + “<span class =’filterRemover’ id='” + selectedItem+ “‘>remove</span>”).appendTo(“#log”);

}

});

$(“#log div span”).each(function() {

//create hidden field for each selected item in the form

var inputOwner = “<input type=’hidden’ name=’parameters[\”OWNER_MANAGER\”]’ value='”+ $(this).attr(“id”) +”‘/>”;

$(inputOwner).appendTo(“#results-filter-form”);

});

//$(“#ownerManagerList”).val(selectedItems);

});

//the remove link is generated dynamically, so live() method should be used here.

$(‘.filterRemover’).live(“click”, function() {

//remove the div that hold the item that has been clicked to remove

$(this).parent().remove();

});

})

Advertisements
This entry was posted in Javascript. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s