Reputation: 14264
The following snippet is not working for me. Basically I want to check if there is an input element with the name "documents[]" and the value item.id and return void.
I thought this line would do it: $("input [name='documents[]'][value='"+item.id+"'") != false
.
However the statement returns true every time. I have looked at the documentation for the jQuery constructor and it doesn't mention anything about returning false if no element is found for the selector.
How can I tell if the selector doesn't match any elements?
$.ajax({
url:'/myid/documents/json_get_documents/'+request.term,
dataType:"json",
success: function(data) {
response($.map(data, function(item){
if($("input [name='documents[]'][value='"+item.id+"'") != false) {
return; //This item has already been added, don't show in autocompete
}
return {
label: '<span class="file">'+item.title+'</span>',
id: item.id,
value: 'Search by title'
}
}))
}
});
Upvotes: 1
Views: 1220
Reputation: 29176
$("input [name='documents[]'][value='"+item.id+"'"]).length
This property will have a length value greater than zero if that element is available in the DOM. You see, when you select an element using jquery's selector, it creates a special array(or you could say, a jquery object) with that element. If multiple elements can be selected with that selector, then the array will contain all of them and if no element matches that selector, the array will have nothing, and in that case it's length property will be zero.
Hope that helps.
Upvotes: 3
Reputation: 186762
You can use .length
. $('lol').length
returns 0
while $('body').length
returns 1.
Upvotes: 2