Click td, select radio button in jQuery

Nick picture Nick · Jan 7, 2011 · Viewed 16.9k times · Source

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!

Answer

Sarfraz picture Sarfraz · Jan 7, 2011

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