I 'm trying to get the text of the td that belong to checked radio buttons, but I can't and my code doesn't work correctly:
<tr>
<td><input name="radio_org_id" type="radio"></td>
<td>male</td>
</tr>
$("body").on("change", "input[name='radio_org_id']:radio:checked", function () {
$('input[name="radio_org_id"]:radio:checked').each(function () {
var vIns_title = $(this).next().find('td').text()
alert(vIns_title)
});
Use $(this).parent().next("td").text()
$("body").on("change", "input[name='radio_org_id']:radio:checked", function() { $('input[name="radio_org_id"]:radio:checked').each(function() { var vIns_title = $(this).parent().next("td").text() alert(vIns_title) }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td><input name="radio_org_id" type="radio"></td> <td>male</td> </tr> <tr> <td><input name="radio_org_id" type="radio"></td> <td>female</td> </tr> </table>
Try this $(this).closest('td').next('td').text()
document for closest()
. And your click function selector was wrong.so change as like this "input[name='radio_org_id']"
$("body").on("change", "input[name='radio_org_id']", function() { $('input[name="radio_org_id"]:checked').each(function() { var vIns_title = $(this).closest('td').next('td').text() console.log(vIns_title) }); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td><input name="radio_org_id" type="radio"></td> <td>male</td> </tr> <table>
Your initial selector is flawed as you only select already checked
elements. The :radio
is also redundant.
To fix your issue, use closest().next()
to get the sibling td
element. Try this:
$('table').on("change", "input[name='radio_org_id']", function() { if ($(this).is(':checked')) { var vIns_title = $(this).closest('td').next('td').text() console.log(vIns_title) } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td><input name="radio_org_id" type="radio"></td> <td>male</td> </tr> <tr> <td><input name="radio_org_id" type="radio"></td> <td>female</td> </tr> </table>
You should also note that you could potentially make this much simpler by placing a value
on the radio input and reading that out in the JS code.
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.