tags:

views:

43

answers:

2

Here's my tr which is inside a form:

        <tr id="mlevel" class="__tr_class__" onclick="needFunction()">
            <td class="checkbox"><input type="radio" name="membership" id="__ID__" value="__ID__" /></td>
            <td class="icon"><img src="__Icon__" width="60" height="60"/></td>
            <td class="name"><h2>__Name__</h2></td>
            <td class="price"><h4>__Price__ for __Days__ Days</h4></td> 
            <td class="auto"><h4>__Auto__</h4></td>
            <td class="auto"><h4>__Active__</h4></td>
        </tr>

When I click on the tr I want the Radio Input to be selected. I would like to use jquery or something simple. Just not sure which way to go. Does anyone know of a simple function to do this?

+3  A: 

You don't really need a function, the following should work:

$('tr').click(
    function() {
        $('input[type=radio]',this).attr('checked','checked');
    }
);


Edited in response to @whatshakin's question:

that works perfectly. Can you explain: $('input[type=radio]',this)

This looks for an element that matches the 'input[type=radio]' using a CSS3 style attribute selector (looking for input elements of type="radio") within the context of this (this being the current object, in this instance the tr).

A slightly more authoritative description/explanation of how this works is at api.jquery.com/jQuery


Edited because it was irritating me that the radio couldn't be un-checked, the following corrects that:

$(document).ready(
  function() {
    $('tr').toggle(
      function(){
        $('input:radio', this).attr('checked',true);
      },
      function() {
        $('input:radio', this).attr('checked',false);
      }
      );
  }
  );

With thanks @Thomas (in comments) for pointing out the erroneous assumption I made in the previous code, that while $(this).attr('checked','checked') evaluates to true, obviously '' wouldn't evaluate to false. Hopefully this approach rectifies that earlier naïveté and silliness.

Also: demo located at jsbin


Edited the above code (the one using toggle()) in response to @Tim Büthe's comment:

Why don't you use the ":radio" pseudo selector?

A pseudo-selector that I didn't even know about until I read his comment, and then visited the jQuery API.

David Thomas
that works perfectly. Can you explain: $('input[type=radio]',this)
whatshakin
In jQuery, you set the attributes 'checked' and 'selected' with value true/false. In this case the value 'checked' will evaluate to true, but it's misleading, because '' will not evaluate to false.
Thomas
Sorry I had to edit that, you answered too soon: $('input[type=radio]',this)
whatshakin
@whatshakin, see the edited answer.
David Thomas
@Thomas, thanks. I'd sort-of half-kinda-realised that but not done anything about it. Since rectified, if you'd be willing to double-check/proof-read for me?
David Thomas
Your code has the same problem as mine, the toggle doesn't work if you click directly on the radio button (that'll only check it, but not uncheck it).
Peter Ajtai
@Peter, well no. But that's not expected behaviour for a radio-button, because that's the native browser action (You can click to de-select a checkbox, but the only way to de-select a radio button is to click on *another* radio-button with the same `name`, or use a `form` reset button).
David Thomas
@David - The drawback to your solution (`.toggle()`) vs mine (use checked state) is that if you have multiple radio buttons, you have to click on a rows twice if you alternately click on the rows: http://jsfiddle.net/ESNAQ/ vs http://jsfiddle.net/LVQS4/ (only 1 click required even with multiple alternate clicks)
Peter Ajtai
Why don't you use the ":radio" pseudo selector?
Tim Büthe
@Tim, honestly? Because I didn't know it existed until now =( ...so, thanks! =D
David Thomas
@Peter, that's true. +1 to you =)
David Thomas
how would you use the pseudo selector?
whatshakin
If you look at the second example-code, you'll see I already edited it to use the pseudo-selector. Here's the [jQuery reference](http://api.jquery.com/category/selectors/#post-639)
David Thomas
+2  A: 

Here's a neat toggle that works without inline Javascript (and with multiple radio buttons):

The Code:

$(function() { // <== Doc ready

    $('tr').click(function(event) {  

        if(event.target.type != "radio") {

            var that = $(this).find('input:radio');
            that.attr('checked', !that.is(':checked'));

        }
    });
});

jsFiddle example


The Breakdown:

  1. Create a .click() handler for all tr elements with $(tr).click()

  2. In the handler assign a variable to the radio button within the tr using $(this).find('input:radio'). This looks through all the descendants of this (the tr clicked) and finds the radio buttons. The jQuery context uses .find() in its implementation, so the previous is synonymous with $('input:radio', this)

  3. Set the checked attribute of the radio button to the opposite of what it is. Things can be checked or unchecked with true or false, and .is(':checked) returns true or false. !that.is(':checked') simply is the opposite of the currently checked state. Note that we don't want to fire this action if the user clicks directly on the radio button, since that'd cancel the native effect of the check, so we use if (event.target.type != "radio").

Peter Ajtai
Why don't you use the ":radio" pseudo selector?
Tim Büthe
@Tim - Good idea. Edited to `input:radio` (simply `:radio` is slower) ==> http://api.jquery.com/radio-selector/
Peter Ajtai
Yes, I meant "input:radio" instead of "input[type=radio]". It's simple and better readable and does the same underneath. However, if you care about performance of this selector, you should add the context "this" like @David Thomas has done, especially if it is a really big document.
Tim Büthe
@Tim - What do you mean "add the context `this`"? I explain in point #2 how `$(this).find('input:radio');` is synonymous with `$('input:radio', this)`. I believe `find()` is probably a little faster, since internally the context is an implementation of `find()`. ---- At any rate, I create the `that` variable and only use `$(this)` once precisely for performance.
Peter Ajtai
@Peter: yes, you are right. You use this, I overread that fact. Then I will say, if you already in a small context like the given. Where you have only a tr-element containing two or three children, performance dosen't matter. You should go for readability in that case.
Tim Büthe
and with overread I mean "i didn't saw it, did not read your answer carefully enough. Man, I should head over to http://english.stackexchange.com/ and find out if "overread" is a real word :-)
Tim Büthe
@Tim - I use `that` for readability, since without defining `that` the following line would be much longer, since `that` is used twice in the line after its definition. So the use of `that` both improves performance and readability. ---- I think it's "misread" ;)
Peter Ajtai
It's a rare occurrence in the English language when use of the words `this` and `that` aids understanding... =)
David Thomas