3

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>

The below jQuery code works,

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

Sometime I have that element as a single element

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

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

SyAu
  • 1,651
  • 7
  • 25
  • 47
  • May I point you towards: "[How do you check if a variable is an array in JavaScript?](http://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript)" – David Thomas Mar 21 '12 at 02:53
  • @DavidThomas I had a look at that before, but I was looking for a jQuery way of doing it. Thanks – SyAu Mar 21 '12 at 03:13

3 Answers3

7

Actually, that code works fine for both one input and two inputs.

But, use the size method to check:

if ($(".p").size() > 1) {
    $(".p").each(function(i){
        alert($(this).value);
    });
}
benesch
  • 5,239
  • 1
  • 22
  • 36
  • Thanks for pointing me that the code is correct. I double checked my original code and noticed I had $('.a')[i] instead of $('.a')[i].value. For information, I have many input type hidden array elements like $('.p'), $('.a') etc. and for easier understanding I simplified my question. – SyAu Mar 26 '12 at 00:38
4

You could check the length of the set jQuery returns.

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 should not reload $('.p') on each iteration. Try this — it'll work with one or multiple matched elements:

$(".p").each(function(){
    alert(this.value);
});
Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69
  • Thanks @Hans Engel. Your answer solved my problem. In fact, all other replies are also useful. – SyAu Mar 21 '12 at 03:10
1

The result of a DOM query is always a jQuery object. It cannot be a single element. $(".p").length will tell you the number of elements in the returned object, which can be 0 if the query matched no objects.

Dmitry Leskov
  • 3,233
  • 1
  • 20
  • 17