Reputation: 4383
I'm new to jQuery. I'm trying to get all inputs inside a div element. Here is what I have coded so far:
$(".pros_earnings_delete_annual_earning").click(function(e) {
e.preventDefault();
var target = $(e.target);
var parent = target.parent(".total-for-earnings");
var inputs = parent.children(":input");
console.log(inputs);
$.each(inputs, function(index, value) {
console.log(value);
});
});
When I click I get this:
[prevObject: v.fn.v.init[0], context: button.pros_earnings_delete_annual_earning, selector: ".parent(.total-for-earnings).children(:input)", constructor: function, init: function…]
The each method does not seem to output anything.
HTML:
<div class="total-for-earnings" style='background-color:#ccc;padding:10px;overflow:hidden;'>
<div style='width:160px;float:left;'><strong>Total for 2013:</strong>
<input type='hidden' name='pros_earnings_annual_year[]' value='2013'>
</div>
<input type='text' name='pros_earnings_annual_amount_mul[]' placeholder='0' value='10' size='8' style='width:80px;' />
<select name='pros_earnings_annual_amount_sup[]' style='width:110px;'>
<option value='Thousand'>Thousand</option>
<option value='Million' selected>Million</option>
<option value='Billion'>Billion</option>
</select><span>USD</span>
<div style="float:right;">
<button class="pros_earnings_save_annual_earning" style="margin-left:15px; width:auto; height:25px;">Save</button>
<button class="pros_earnings_delete_annual_earning" style="margin-left:15px; width:25px; height:25px;">-</button>
</div>
</div>
Upvotes: 0
Views: 127
Reputation: 5632
Change
var target = $(e.target);
var parent = target.parent(".total-for-earnings");
var inputs = parent.children(":input");
to,
var parent = $(this).closest(".total-for-earnings");
var inputs = parent.find(":input"); //Unlike children(), find() will go any depth to match.
Upvotes: 1
Reputation: 56509
the problem is in this line
var parent = target.parent(".total-for-earnings");
change to
var parent = target.parents(".total-for-earnings");
Upvotes: 0
Reputation: 136104
Simply put:
var $inputs = $(':input',parent)
Will match all inputs in the context of the parent element.
You're console.log
is outputting the jQuery object which represents each item in this collection, if you want the value of the input, just ask:
$inputs.each(function(){
console.log($(this).val());
})
Also, there was one other bug - target.parent(..)
should have been target.parents(..)
(plural)
Live example: http://jsfiddle.net/3aJuZ/
Upvotes: 1