My goal is to set only one of the following two checkboxes to be selected at a time.
The jQuery only captures the elements of the parent layer(staffTypeSet), but cannot capture those of the child layer(.staffType2).
$('.staffType2').click(function () {
$(".staffType2").not(this).removeAttr("checked");
});
The JavaScript code I designed is not having any effect. What could be the reason for this problem? Do you have any solutions or ideas? Thank you.
2
Answers
The correct way to uncheck a checkbox is to use the
.prop()
method instead of.removeAttr()
.Here’s the corrected sample code:
However, if you want to allow only one checkbox to be selected at a time, I recommend using radio buttons instead. Radio buttons are designed for this purpose, and you won’t need any additional jQuery code to achieve the desired behavior.
To use radio buttons, change the input type to radio and give them the same name attribute. For example:
With radio buttons, only one can be selected at a time within the group with the same name attribute.
Becase prop and attribute are different.
Use
prop
instead ofremoveAttr
Like this example from your question
Google key word for differnece between prop and attribute =>
attr prop jquery difference