问题
I have this html -
<ol class="subproduct">
<li>
<input type="checkbox" name="extra2" value="Multidispositivo" />
<p class="checkbox"></p>
<h3>test<span class="price"><span>+2</span>€</span></h3>
<p>test words</p>
</li>
<li>
<input type="checkbox" name="extra2" value="Multidispositivo" />
<p class="checkbox"></p>
<h3>test</h3>
<p>test words</p>
</li>
<li>
<input type="checkbox" name="extra2" value="15 min extra" />
<p class="checkbox"></p>
<h3>test/h3>
<p>test words</p>
</li>
<li>
<input type="checkbox" name="extra2" value="Multidispositivo" />
<p class="checkbox"></p>
<h3>test</h3>
<p>test words</p>
</li>
</ol>
which I need to add a class to the li on 'checking' the checkbox. Currently I use this
$(document).ready(function() {
$('.subproduct input:checkbox').change(function(){
if($(this).is(":checked")) {
$(this).parent().toggleClass("checked");
}
});
});
but I need it so that only ever one checkbox is checked by the user so if they check another box it removes the class of any other
How is this possible?
回答1:
See this: Sample
$(document).ready(function() {
$('.subproduct input:checkbox').change(function(){
$('.subproduct input:checkbox').not(this).attr("checked",false);
$(".subproduct li").removeClass("checked");
if($(this).is(":checked")) {
$(this).parent().toggleClass("checked");
}
});
});
回答2:
remove the class of all <li>'s on chnage event... using removeClass();...and then if checked toggleClass() of that <li>
try this
$(document).ready(function() {
$('.subproduct input:checkbox').change(function(){
$(".subproduct li").removeClass("checked"); //<---here
if($(this).is(":checked")) {
$(this).parent().toggleClass("checked"); // and using addClass("checked") here is better ..
}
});
});
回答3:
Try this http://jsfiddle.net/QHuV9/4/
$(document).ready(function() {
$('.subproduct input:checkbox').change(function(){
if($(this).is(":checked")) {
$(this).parent("li").addClass("checked");
}
else {
$(this).parent("li").removeClass("checked");
}
});
});
I hope i am taking your question rite
回答4:
The simplest solution is something like:
$(document).ready(function() {
$('.subproduct input:checkbox').change(function(){
if($(this).is(":checked")) {
$(this).parent().siblings().removeClass('checked');
$(this).parent().addClass("checked");
}
});
});
And I would advise to use <input type="radio"> so that the behavior will be understood by user.
回答5:
try this DEMO
$(document).ready(function() {
$('.subproduct input:checkbox').change(function(){
if($(this).is(":checked")) {
$(':checkbox').prop('checked',false);
$('ol li').removeClass('checked');
$(this).prop('checked',true);
$(this).parent().addClass('checked');
} else {
$(this).parent().removeClass('checked');
}
});
});
来源:https://stackoverflow.com/questions/15359039/how-to-i-uncheck-boxes-when-checking-others-with-jquery