views:

57

answers:

2

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'
                }
            }))
        }
    });
+2  A: 

You can use .length. $('lol').length returns 0 while $('body').length returns 1.

meder
Yes, a `jQuery` function call (with a selector and optionally the context) will always return a jQuery collection object, which contains the `length` property - or the number of elements matched.
CD Sanchez
+1  A: 
$("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.

Night Shade