Allen Allen - 2 months ago 16
jQuery Question

jQuery .each for Sub-elements

I'm trying to use jquery and it's each function to the get values in this type of structure:

<div id="test">
<p><input name="name1" value="Z1"></p>
<p><input name="name2" value="Z2"></p>
<p><input name="name3" value="Z3"></p>
<p><input name="name4" value="Z4"></p>
</div>


I've tried using

$('#test').find('input').each(function () { }
$('#test > p').children('input').each(function () { }


but the value I get using
alert($(this).value);
is always 'undefined'. Any ideas what might be going on?

Answer

Alternatively you can use the selector #test input that will retrieve all the inputs on the div, which you'll be able to quickly access throught the .each() method, like so:

var values = [];
$('#test input').each(function (){
    values.push($(this).val());
});
console.log(values);

Check this jsFiddle for more information.

Hope it helps. Cheers.

Comments