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 ie select
, I want to print values of siblings ie 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>
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);
});
});
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.