Click td, select radio button in jQuery

亡梦爱人 提交于 2019-12-09 16:41:09

问题


Got a small problem with some very basic jQuery, I'd like to be able to click on a table cell, and then have it automatically select the radio button inside.

HTML:

  <table>
   <tr>
    <td>
     1<br>
     <input type="radio" name="choice" value="1">
    </td>
    <td>
     2<br>
     <input type="radio" name="choice" value="2">
    </td>
    <td>
     3<br>
     <input type="radio" name="choice" value="3">
    </td>
   </tr>
  </table>

jQuery:

 $("td").click(function () {

  $(this).closest('input:radio').attr('checked',true);

 });

Any help would really be appreciated, thank you!


回答1:


Use this selector:

$('input:radio', this).attr('checked', true);

Or using find method:

$(this).find('input:radio').attr('checked', true);

Here is how your code should look like:

$("td").click(function () {
   $(this).find('input:radio').attr('checked', true);
});



回答2:


Try

$(this).find('input:radio').attr('checked','checked');



回答3:


Try find instead of closest.

$(this).find('input:radio').attr('checked',true);



回答4:


This works perfectly

 $(function () {
        $('td').click(function () {

        var cell = $(this),
            state = cell.data('state') || 'first';

        switch (state) {
            case 'first':
                cell.data('state', 'second');
                cell.find('input:radio').attr('checked', true);
                cell.find('input:radio').data('checked', true);
                cell.find('input:radio').prop('checked', true);
                break;
            case 'second':
                cell.data('state', 'first');
                cell.find('input:radio').attr('checked', false);
                cell.find('input:radio').data('checked', false);
                cell.find('input:radio').prop('checked', false);
                break;
            default:

                break;
        }
    });
});


来源:https://stackoverflow.com/questions/4625037/click-td-select-radio-button-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!