问题
I have some divs. Each of them contains two checkbox (each checkbox is in a div of a same class 'class3'). I would that when the user checks the first checkbox, the second one is checked and disabled. I've tried with :
$('.class1').live('click', function () {
var n = $(this).siblings('input:checkbox');
if ($(this).attr('checked')) {
n.attr('disabled', true);
} else {
n.attr('disabled',false);
}
return false;
});
In this way the two checkbox are enabled, but when I click on the first one, the check doesn't appear and nothing happens.
<div class="elements">
<div class="class3">
<input class="class1" type="checkbox" value="1" name="first" id="first" />
</div>
<div class="class3">
<input class="class2" type="checkbox" value="1" name="second" id="second" />
</div>
</div>
回答1:
You can attach an event to each first checkbox of divs of class1 by using something like:
$('.class1 input:first-child').live('change', function () {
(I've used change instead of click because it's a bit more generic. ) Only attaching the first element and not the entire div makes sure you only react when needed.
Futher the disabling as you have used it should work, but siblings will only work if your first checkbox is not nested inside another element (e.g. a Paragraph)
Example fiddle: http://jsfiddle.net/Zqz63/
edit Seeing the html in your updated post , siblings will indeed not work, you could look up in the parents chain to find the .elements div and look down for there for checkboxes (other than the selected)
var n = $(this).parents('.elements').find('input:checkbox').not(this);
jsfiddle is unresponsive, so I've moved the sample to jsbin: http://jsbin.com/ahemet/3/edit (NB, in the current jsbin version there is no proper selection of only the first checkbox, so the event will also fire on the 2nd checkbox, but I reckoned that was outside the scope of your question)
edit 2 Using the information that class1 is always the first checkbox and class2 always the second:
$('input:checkbox.class1').live('change', function () {
var n = $(this).parents('.elements').first().find('input:checkbox.class2');
if ($(this).attr('checked')) {
n.attr('checked',true);
n.attr('disabled', true);
} else {
n.attr('disabled',false);
}
});
test: http://jsbin.com/ahemet/4/edit
回答2:
$('.class1').live('click', function () {
var n = $(this).siblings('input:checkbox');
if ($(this).attr('checked')) {
n.prop('disabled', true);
} else {
n.prop('disabled', false);
}
});
回答3:
When you return false; you prevent the default behaviour of that event from occurring; in the case of clicking on a checkbox, the default behaviour is checking the checkbox. Simply remove the return false; as it does nothing positive for you.
In addition, disabled is a property of an element, so you should be using the .prop() function to set/modify its value, not the .attr() function.
来源:https://stackoverflow.com/questions/11240672/jquery-check-and-disable-checkbox-on-checking-another-checkbox