Reputation: 712
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?
Upvotes: 0
Views: 89
Reputation: 657
$('#test input').each(function(i,v){
console.log($(this).val());
});
Explanation: We have a selector of '#test input'
which means that we are searching for all input
s directly or transitively inside #test
. So far, so good. However, we need their value
s, therefore, inside the function we log the result of $(this).val()
which will output the values to the console.
Upvotes: 0
Reputation: 1526
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.
Upvotes: 1
Reputation: 562
first one is working mate. I am not sure what's your problem.
https://jsfiddle.net/tsj0w29x/ $('#test').find('input').each(function () {
alert($(this).value);
}
Upvotes: 0
Reputation: 2864
Your two methods of retrieving the elements will work just fine. You're seeing undefined
because of how you're accessing the input value: .val()
not .value
.
So:
$('#test').find('input').each(function() {
$(document.body).append($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
Upvotes: 2
Reputation: 147
You should go through each <p>
tag because they have other siblings, and then in the each function find the input and get the value.
This will work:
$('#test > p').each(function(){
var value = $(this).find('input').val();
});
Upvotes: 0