I have a scenario like below:
I have to add the attribute 'checked' on the radio button which having the header 'MyHeader2'
<table> <tr> <th> MyHeader </th> <th> MyHeader2 </th> </tr> <tr> <td> <input type='radio' name='testradio' /> </td> <td> <input type='radio' name='testradio1' /> </td> </tr> </table>
How to implement this in jQuery?
Try this:
$("table tr th:contains(MyHeader2)").each(function(){
var i = $(this).index(); //Get the index of the th.
$("table tr td:eq("+i+") input:radio").prop("checked",true); // Set the radio to checked.
})
demo
$("table tr th:contains(MyHeader2)").each(function() { var i = $(this).index(); $("table tr td:eq(" + i + ") input:radio").prop("checked", true) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <th> MyHeader </th> <th> MyHeader2 </th> </tr> <tr> <td> <input type='radio' name='testradio' /> </td> <td> <input type='radio' name='testradio1' /> </td> </tr> </table>
You better consider using data-attributes
where you need things like this.
Makes life easy for you.
Just add heading as data property to checkbox like
data-heading="MyHeader"
And then it'll be easy for you to select it like
$("input[data-heading='MyHeader2']")
$("input[data-heading='MyHeader2']").prop("checked", true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table> <tr> <th> MyHeader </th> <th> MyHeader2 </th> </tr> <tr> <td> <input type='radio' data-heading="MyHeader" name='testradio' /> </td> <td> <input type='radio' data-heading="MyHeader2" name='testradio1' /> </td> </tr> </table>
You can first get the header index based on the value of header MyHeader2
. Using this index you can select the radio button in the td
and mark it checked.
$(document).ready(function(){ var headerValue = 'MyHeader2'; $('table tr th').each(function(index){ if($(this).text().trim() === headerValue){ headerIndex = index; } }); $('table tr').each(function(){ $(this).find('td:eq('+headerIndex+')').find('input[type=radio]').prop("checked", true); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table> <tr> <th> MyHeader </th> <th> MyHeader2 </th> </tr> <tr> <td> <input type='radio' name='testradio' /> </td> <td> <input type='radio' name='testradio1' /> </td> </tr> <tr> <td> <input type='radio' name='testradio3' /> </td> <td> <input type='radio' name='testradio4' /> </td> </tr> </table>
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.