简体   繁体   English

如何根据该列标题检查表行中的单选按钮?

[英]How to check a radio button in the table row based on that column header?

I have a scenario like below: 我有一个类似下面的场景:

I have to add the attribute 'checked' on the radio button which having the header 'MyHeader2' 我必须在具有标题“ 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? 如何在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. 您最好考虑在需要此类data-attributes地方使用data-attributes

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 . 您可以首先根据标头MyHeader2的值获取标头索引。 Using this index you can select the radio button in the td and mark it checked. 使用该索引,您可以选择td的单选按钮并将其标记为选中状态。

 $(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM