Reputation: 1253
Earlier in the day I got stuck with jquery's
find
method working. And now I am unable to fetch nested elements from my html table below:
what I am trying to do : on each checkbox selected columns i.e. select
, I want to print values of siblings i.e. name
and address
but I am unable to do that. Below is my code:
$("#but").click(function(){
$(".tabclass tr td input[type='checkbox']:checked").each(function(){
var sibs=$(this).siblings("td");
var v1=$(sibs[0]).text();
var v2=$(sibs[1]).children[0].val();
alert(v1+" & "+v2);
});
});
HTML Code:
<body>
<table border="1" class="tabclass">
<th>select</th>
<th>Name</th>
<th>Address</th>
<tr>
<td>
<input type="checkbox" name="selectCheck" class="select" id="ch1" value="1" /> </td>
<td><span class="name">Nitin</span></td>
<td>
<select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="selectCheck" class="select" id="ch2" value="2" /> </td>
<td><span class="name">Abc</span></td>
<td>
<select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="selectCheck" class="select" id="ch3" value="3" /> </td>
<td><span class="name">Xyz</span></td>
<td>
<select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select>
</td>
</tr>
</table>
<br>
<br>
<button id="but">Test</button>
</body>
Upvotes: 1
Views: 59
Reputation: 55740
You have 2 issues with the code
Change
var sibs=$(this).siblings("td");
to
var sibs=$(this).parent().siblings("td");
.children[0]
gives you a DOM
object, which does not have the val()
method.Replace
var v2=$(sibs[1]).children[0].val();
with
var v2 = $('select', sibs[1]).val(); OR var v2=$(sibs[1]).children()[0].value;
Also use console.log
instead of alert
as the latter stops the thread on which the UI runs.
JS
$("#but").click(function() {
$(".tabclass tr td input[type='checkbox']:checked").each(function() {
var sibs = $(this).parent().siblings("td");
var v1 = $(sibs[0]).text();
var v2 = $('select', sibs[1]).val();
alert(v1 + " & " + v2);
});
});
Upvotes: 2
Reputation: 18987
Problem: Is that the check box is child of td
and it doesn't have any siblings. As per your this code var sibs=$(this).siblings("td");
it fetches nothing .
Solution: Is to go one level up to its parent ie:td
and now this td
has siblings. So use this code
var sibs=$(this).parent().siblings("td");
Also change $(sibs[1]).children[0].val();
To
$(sibs[1]).children('select').val();
Upvotes: 1