422
422

Reputation: 5770

OnClick add class to label

I am working on a quiz script. I have hidden the radio buttons and wanting to make the label class ( radio button pseudo ) clickable.

I have:

<li class="pos-3">
   <input type="radio" value="4" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'/>
   <label class="" for="radio1_<?php echo $result['id'];?>"><?php echo $result['answer4'];?></label>
</li>

I thought I could achieve this with jQuery like:

$(document).ready(function() {
 if($("input.check").is(":checked")){
$(this).label.addClass("checked");
  }
});

But failing miserably.

Any suggestions, the radio click is registering. But the class isnt being added.

There are 4 ( li's ) choices for each question.

Upvotes: 0

Views: 1841

Answers (2)

Felix
Felix

Reputation: 38112

You can just add class checked to clicked radio button and remove that class from other radio buttons like this:

$('input[type="radio"]').change(function () { 
    $('input[type="radio"]').next().removeClass('checked');
    $(this).next().addClass('checked');    
});

Demo

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388406

You need to have a change handler registered for the radio elements, then you can use .toggleClass() to switch the checked class for the label

jQuery(function () {
    $('input[type="radio"]').change(function () {
        $('input[name="' + this.name + '"]').not(this).next().removeClass('checked');
        $(this).next().toggleClass('checked', this.checked)
    })
})

Demo: Fiddle

Upvotes: 2

Related Questions