开发者

Radio button checked status with jQuery

Here is the basic code

<ul>
 <li>
  <input type="radio" name="r" value="a" id="a" checked="checked" />
  <label for="a">A</label>
 </li>
 <li>
  <input type="radio" name="r" value="b" id="b" />
  <label for="b">B</label>
 </li>
</ul>

So I need to have it work as:

1 Click on the <label> and check if the sibling <radio> is checked="checked" then add "selected" class to the parent <li>

2 Click on the <label> and check if the sibling <radio> is NOT checked then ad开发者_开发知识库d checked="checked" to the sibling <radio> and add "selected" class to the parent <li> also remove all the other "checked" and "selected" in the <ul>

Could you help me please!


Clicking on the label should check the radio buttons automatically in the browser. So, you just need do add a click event to the label/input that will set the class on the li's.

Something like this should work:
HTML (I just added id="mylist")

<ul id="mylist">
 <li>
  <input type="radio" name="r" value="a" id="a" checked="checked" />
  <label for="a">A</label>
 </li>
 <li>
  <input type="radio" name="r" value="b" id="b" />
  <label for="b">B</label>
 </li>
</ul>

JavaScript

$(function() {
 $("#mylist input, #mylist label").click(function() {
  $("#mylist li").removeClass("selected");
  $(this).parent().addClass("selected");
 });
});


Since you're already using label with the for attribute there should really be no need to attach an event to the label element, unless you need to contend with IE6 making you're life difficult.

$(':radio[name="r"]').change(function(){
    $(this).parent('li').addClass('selected').siblings().removeClass('selected');
}).filter(':checked').change();

Documentation for: change()

See: http://www.jsfiddle.net/yijiang/mzPk9/


I'm sure this isn't the most elegant way but with a change to your markup (adding class 'a' and 'b' to your li - basically the same value as the id of the radio elem. contained) here we go:

$('label').click(function(){
    // if the radio is already checked
    if ($('#'+$(this).attr('for')).attr('checked') == 'checked') {
        $('ul li').removeClass('selected');  // remove previous selected items
        $('.'+$(this).attr('for')).addClass('selected'); // add new selected item
    } else {
        // radio not checked
        $('#'+$(this).attr('for')).attr('checked','checked'); // check radio (altough this should be automatic, without js
        $('ul li').removeClass('selected'); // clear previous selected items
        $('.'+$(this).attr('for')).addClass('selected'); // add new selected item
    }
});

For speed, I would suggest adding an id to the ul, say "list" and have the code change from

$('label').click(function(){

to

$('#list label').click(function(){

Also, from:

$('ul li').removeClass('selected');  // remove previous selected items

to

$('#list li').removeClass('selected');  // remove previous selected items

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜