Question

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!

Was it helpful?

Solution

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);
});

OTHER TIPS

Try

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

Try find instead of closest.

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

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;
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top