Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Radio Button when clicking DIV

Tags:

html

jquery

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?

like image 943
Ian Avatar asked Jul 17 '09 20:07

Ian


1 Answers

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.

like image 53
romaninsh Avatar answered Oct 03 '22 02:10

romaninsh