开发者

How to chain jQuery removeAttr for radios inside a Div

I have a checkbox that shows/hides a div that contains a grid of radio buttons. At the bottom of my page I have this jQuery:

$(document).ready(function(){
  $('#cb1_1').click(function(){ $('div#QxGrid').slideToggle('slow');
 });
});

And this works great. When the radio buttons are hidden though I would like the page to auto-uncheck any radios that were selected, so I tried cha开发者_如何学编程ining a removeAttr('checked'):

$('#cb1_1').click(function(){ $('div#Qx1').removeAttr('checked').slideToggle('slow'); });

This doesn't work... Is that because the jQuery is expecting a radio with id Qx1? (not a bunch of radios inside the Qx1 div?) HTML extract (abbreviated) looks like

<div id="Qx1">
  <p class="ans">
    <input type="radio" name="q1" id="q11" value="1"> etc.
    <input type="radio" name="q1" id="q12" value="2"> etc.
    <input type="radio" name="q1" id="q13" value="3"> etc.
  </p>
</div>


$('div#Qx1').find('input[type=radio]').removeAttr('checked').end().slideToggle('slow');

edit: True, Endophage:

$('div#Qx1').slideToggle('slow').find('input[type=radio]').removeAttr('checked');

that way you don't need the end()


Correct. The way you have it, it wants to remove the attribute "checked" from the div. Just add another line inside the click() to uncheck anything that's checked:

$(document).ready(function(){
  $('#cb1_1').click(function(){ 
    $('p.ans').children('input').removeAttr('checked');
    $('div#Qx1').slideToggle('slow');
 });
});


The div doesn't have an attribute checked as it shouldn't which is why this isn't working. The following should work, note the order of the chained methods is very important as you want to do everything required with the div before traversing to its children radio inputs:

$('#q1voc_1').click(function()
{ 
    $('div#Qx1').slideToggle('slow').children('input[type=radio]').each(function()
    {
        $(this).removeAttr('checked');
    }); 
});

I'd have to try it but you may also be able to simplify the $('div#Qx1')... part to:

$('div#Qx1').slideToggle('slow').children('input[type=radio]').removeAttr('checked');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜