Click td, select radio button in jQuery
Asked Answered
O

4

7

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!

Orvil answered 7/1, 2011 at 11:30 Comment(1)
Since the answers are already correct, I'll just add here that .closest() is for traversing up the DOM tree, e.g. getting the <tr> or the <table>, rather than down.Industrials
T
14

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);
});
Toffey answered 7/1, 2011 at 11:31 Comment(4)
No need to wrap this in the jQuery constructor when used as a context, $('input:radio', this) is enough.Industrials
Thank you so much! One quick thing though, I'm changing the class when the radio button is selected, but this doesn't work when you click the cell, even though the radio button is selected? $("td input[type=radio]").bind('change click', function () { $('td').removeClass('selected'); $(this).parent('td').addClass('selected'); });Orvil
@Box9: Updated to avoid any further confusion :)Toffey
@Nick: You should post that as another question :)Toffey
O
2

Try

$(this).find('input:radio').attr('checked','checked');
Obadiah answered 7/1, 2011 at 11:33 Comment(0)
A
2

Try find instead of closest.

$(this).find('input:radio').attr('checked',true);
Aright answered 7/1, 2011 at 11:38 Comment(0)
D
1

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;
        }
    });
});
Divisive answered 27/2, 2019 at 1:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.