How to remove value from hidden field using jquery.autocomplete
I have a page with two inputs: users_list
and users_ids
. jquery.autocomplete is used to autocomplete the users_list
. users_ids
is hidden field. When the user is selected and added to the users_list
his id is added to the users_ids
. Everything works fine. But the question is how to rem开发者_JAVA百科ove the value from user_ids
if the user is removed from users_list
?
The script:
$(document).ready(function(){
function formatItem(row) {
return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
$("#users_list").autocomplete("<%= url_for(:controller => :users,
:action => :autocomplete_users_list) %>",
{
multiple: true,
matchContains: true,
mustMatch: true,
autoFill: true,
formatItem: formatItem,
formatResult: formatResult
});
$("#users_list").result(function(event, data, formatted) {
var hidden = $("#users_ids");
hidden.val( (hidden.val() ? hidden.val() + ";" : hidden.val()) + data[1]);
});
});
It seems that your question has nothing to do with jquery autocomplete... You want to remove an item from a serialized array. So: Your hidden field value is like this: id;anotherid;onelastid So the code would be:
function remove_id_from_hidden(id) {
var hidden = $("#users_ids");
var arr = hidden.val().split(";"); # transforms the string into an array
arr.splice(arr.indexOf(id), 1); # removes the item from the array
hidden.val(arr.join(";")); # sets the value again
}
I have a hiddenfield where i stored the ids of the selected values.
In order to catch when there is no value, and the users has removed a value i use:
$('input.autocomplete').blur(function () {
if ($.trim($(this).val()) < 1) {
$(this).siblings('input[type="hidden"]').val(0);
}
});
$('input.autocomplete').autocomplete(/* autocomplete code */);
the blur event catches when users moves focus from autocomplete input box and sets hiddenfield to 0, independently of what autocomplete does.
精彩评论