Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is array[0] returning a different object than array.first using jQuery and why can't I use .val( )?

I'm selecting an array of input objects using jQuery and I'm running into an interesting problem when I try to chain together multiple methods after selecting one of the array elements. Can anyone explain to me why I get this behavior?

jQuery('.custom-size').first().find('input:hidden')
returns =>  

[<input id=​"custom_order_custom_sizes_attributes_0_size_id" name=​"custom_order[custom_sizes_attributes]​[0]​[size_id]​" type=​"hidden" value=​"138">​
, 
<input name=​"custom_order[custom_sizes_attributes]​[0]​[_destroy]​" type=​"hidden" value=​"0">​
]

If I select one of the elements using jQuery .first() or .last() and then call .val(), I get the expected value of "138".

When I try to use a location in the array, I can return the element of the array:

var input = jQuery('.custom-size').first().find('input:hidden')[1]
returns => 
<input name=​"custom_order[custom_sizes_attributes]​[0]​[_destroy]​" type=​"hidden" value=​"0">

I can't call .val() on this object however. Instead I get this error message:

TypeError: Object #<HTMLInputElement> has no method 'val'

I can use .slice(x,y) to return the single element, but this seems rather silly. What am I missing here.

like image 250
Paul Avatar asked Nov 23 '12 08:11

Paul


1 Answers

The following code:

$(".something")[0]

gets a single DOM element from the jQuery set. This code does the same as if you do

document.getElementsByClassName("something")[0]

Retrieved DOM element doesn't have val() method, since it is not a jQuery object.

In order to get the first jQuery object from jQuery set, you may use either :eq() selector (or .eq() method), or :first selector (or .first() method):

$(".something:eq(0)");   // $(".something").eq(0);
$(".something:first");   // $(".something").first();
like image 186
VisioN Avatar answered Oct 20 '22 00:10

VisioN