JQuery - How to check if element is array or single

jQuery 1.7.1

Sometimes I have an element as an array,

<tr><td><input type="hidden" class="p" name="it" value="1"/></td></tr>
<tr><td><input type="hidden" class="p" name="it" value="2"/></td></tr>

      

Below is the jQuery code,

$(".p").each(function(i){
alert($('.p')[i].value);
});

      

Sometime I have this item as one item

<tr><td><input type="hidden" class="p" name="it" value="1"/></td></tr>

      

I want to make sure the hidden input is an array or a single element before trying the above jQuery code. How can I do this using jQuery?

+3


source to share


3 answers


Actually, this code works great for both single input and two inputs.

But use the method size

to check:



if ($(".p").size() > 1) {
    $(".p").each(function(i){
        alert($(this).value);
    });
}

      

+7


source


You can check the length

jQuery returned set.

var p = $('.p');
if ( p.length == 1 )
    // single
else if ( p.length > 1 )
    // set

      




But this, I believe, is not your problem. Your jQuery code shouldn't reload $('.p')

on every iteration. Try this - it will work with one or more elements:

$(".p").each(function(){
    alert(this.value);
});

      

+3


source


The result of a DOM query is always a jQuery object. It cannot be one element. $(".p").length

will tell you the number of elements in the returned object, which can be 0 if the query did not match any objects.

+1


source







All Articles