11

I'm writing a quiz application using php / jquery. The answer selections are contained like so:

<ul id="answers"> 
    <li> 
        <div> 
        <input type='radio' name='answer_id' value='313'> True
        </div> 
    </li> 
    <li> 
        <div> 
        <input type='radio' name='answer_id' value='314'> False
        </div> 
    </li> 
</ul> 

After being styled w/ css, these answers appear in a container with one answer per line. Each answer has its own box inside the container. I want the user to be able to click anywhere inside the individual answer div and have the radio select become checked.

How can I activate the radio button check when a user clicks in the radio button's container div, using jquery?

Ian
  • 11,920
  • 27
  • 61
  • 77

4 Answers4

25

Instead of using jQuery, this can all be done in native HTML using the <label> element. Here is a sample of it in action.

<ul id="answers"> 
        <li> 
                <label> 
                    <input type='radio' name='answer_id' value='313'> True
                </label> 
        </li> 
        <li> 
                <label> 
                    <input type='radio' name='answer_id' value='314'> False
                </label> 
        </li> 
</ul>
TJ L
  • 23,914
  • 7
  • 59
  • 77
2

Correct usage of the label tag is:

<input type="checkbox" id="checkme" name="checkme" /> <label for="checkme">Toggle this checkbox on/off</label>

for="..." always makes reference to the input's id.

2

I agree with tj111, but if does not always suit:

  • More difficult to style.
  • labels only work if there is text in them (thanks Michael)

Here is the alternative code using div and jQuery:

$('input:radio').click(ev){
    ev.stopPropagation();
}).parent().click(function(ev){
    ev.preventDefault();
    $(this).children('input').click();
    $(this).addClass('active').siblings().removeClass('active');
});

With the "active" class now you can even hide the radios and use stylesheet for highlighting.

romaninsh
  • 10,606
  • 4
  • 50
  • 70
  • That's... interesting. How about: $('input:radio').click(function (ev) { ev.stopPropagation(); }).parent().click(function (ev) { ev.preventDefault(); $(this).children('input').click(); }); – Michael Paulukonis Apr 03 '13 at 16:58
  • I found that labels only worked when there was text (or a significant amount of whitespace) available for clicking. Conversely, putting the click onto the parent would screw up the actual radio-click itself. Reworking romaninsh's code solved my problem – Michael Paulukonis Apr 03 '13 at 17:02
0

maybe something like:

$('#answers li div').click(function(){

  var r = $(this).find('input[type=radio]');
  if($(r).is(":checked"))
  {
    $(r).attr("checked", "");
  }
  else
  {
    $(r).attr("checked", "checked");
  }

});
John Boker
  • 82,559
  • 17
  • 97
  • 130