问题
I have a simple slideToggle setup that opens a div on a page. Some of the divs have a self test in them. I'm having trouble figuring out how to reset the radio buttons when the div is closed. Here is the jQuery:
$("h2.titleTrigger").click(function(e){
e.preventDefault();
//TOGGLE OPEN/CLOSE THE DIV
$(this).toggleClass("active").next().slideToggle("fast");
return false;
});
//self test
$('input:radio').bind('change',function(e){
e.preventDefault();
var parentId = $(this).parents('.selfTest').attr('id');
$('#'+parentId+' .selfTestWrong').addClass('answerShown');
$('#'+parentId+' .selfTestAnswer').slideDown(300);
});
See it working here: http://jsfiddle.net/3XBgu/
What is the best way to reset the self test to it's un-selected state when the user closes the slideToggle?
回答1:
You can do this:
$("h2.titleTrigger").click(function (e) {
e.preventDefault();
//TOGGLE OPEN/CLOSE THE DIV
$(this).toggleClass("active").next().slideToggle("fast");
// Re-set all the radio buttons
$('input:radio').prop('checked', false);
// Re-set all the labels class
$('.selfTestWrong').removeClass('answerShown');
return false;
});
FIDDLE
回答2:
This solves your problem:
//TOGGLE OPEN/CLOSE THE DIV
$(this).toggleClass("active").next().slideToggle("fast");
$(".hey").each(function(){
this.checked = false;
$('.selfTestWrong').removeClass('answerShown');
$('.selfTestAnswer').hide();
});
return false;
});
(Added class="hey" to each input)
http://jsfiddle.net/3XBgu/2/
来源:https://stackoverflow.com/questions/16220747/how-to-reset-selected-radio-buttons-when-closing-slidetoggle