jQuery element variable doesn't seem to be accessible?
So I get a set of form elements that I want to extract the values from, by using
var inputs =开发者_开发知识库 $("input.row_2");
inputs[0].val()
When I run this, I get told that val is not a valid method.
What am I doing wrong?
Should be an easy one..
Thanks!inputs[0]
returns you the DOM element, so inputs[0].value
will have what you want.
You can also use inputs.eq(0).val()
which will never complain that inputs[0]
is undefined if there are no matches.
.eq()
returns a jQuery object (not DOM) as opposed to .get()
which is also what you will get from using [0]
A jQUery object behaves like an array of DOM elements.
Therefore, inputs[0]
returns the raw DOM element, not a jQuery wrapper.
Since raw DOM elements do not have a val()
method, you're getting an error.
To call jQuery methods on a specific element, you should call the eq()
method, like this:
inputs.eq(0).val();
In your case, you can also simply get the value
property from the raw DOM element, like this:
inputs[0].value
Note, however, that this will not behave like jQuery's val()
for <select>
elements.
$('input.row_2').first().val();
精彩评论