跨度文本为True,则选中单选按钮,否则未选中

时间:2019-02-17 09:19:52

标签: javascript jquery html

请仔细阅读此问题。

当跨页文本在pageLoad上为“ True”时,我希望选中复选框值。 下面的示例非常适合单选按钮单击,然后跨度值变为“ true”或“ false”。

代码

$('table').on('change', ':radio', function () {
    $(this).next('span').text('True').closest('td')
           .siblings().find('span').text('False');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td> <input  type='radio' name='attandance' ><span>False</span></td>
<td> <input  type='radio' name='attandance' ><span>False</span></td>
<td> <input  type='radio' name='attandance' ><span>False</span></td>
</tr>
</table>

我想如果span值是true,那么单选按钮会自动检查。 Here is Attachment

谢谢。

2 个答案:

答案 0 :(得分:0)

$('table')
  .on('change', ':radio', function () {
    $(this).next('label').text('True').closest('td')
           .siblings().find('label').text('False');
  })
  .find('label').filter(function(){
    return $(this).text().toLowerCase() === 'true';
  }).closest('td').find('input').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td> <input type='radio' name='attandance' id="opt1"><label for="opt1">False</label></td>
<td> <input type='radio' name='attandance' id="opt2"><label for="opt2">True</label></td>
<td> <input type='radio' name='attandance' id="opt3"><label for="opt3">False</label></td>
</tr>
</table>

我也将span更改为label,因为这是一个好习惯。但是本质是:找到标签/跨度,检查文本,然后上一层查找并更改input

答案 1 :(得分:0)

@faizan,我可以看到您已经准备好进行onchange的功能,而且您只需要在页面/文档加载时更改值即可。

我建议您可以使用$(document).ready()功能。

$(document).ready()函数下面,当找到真值时,将自动将单选按钮设置为选中状态。

      $('table').on('change', ':radio', function () {
            $(this).next('span').text('True').closest('td')
                   .siblings().find('span').text('False');
        });

// Page load event to checked the true value 
    $(document).ready(function(){
      $("table td").each(function(i, obj){
        var value = $(obj).find("span").text();
        
        if(value === "True"){
          $(obj).find("input[type='radio']").prop("checked",true);
        }
      })
    })
     
       <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <table>
        <tr>
        <td> <input  type='radio' name='attandance' ><span>False</span></td>
        <td> <input  type='radio' name='attandance' ><span>True</span></td>
        <td> <input  type='radio' name='attandance' ><span>False</span></td>
        </tr>
        </table>

我建议您在表格中使用特定的ID,这将使jQuery在页面中选择特定的表格更为容易。

 <table id="tblAttendance">
相关问题