Tôi hy vọng this một người sẽ làm việc
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
Javascript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
tốt, nút radio nên là một được sử dụng trong các tùy chọn loại trừ lẫn nhau, mặc dù tôi đã gặp phải một kịch bản mà khách hàng ưa thích có số không cho một mục đã chọn và hộp kiểm javaScript'ed hoạt động tốt.
Cập nhật
Nhìn vào câu trả lời của tôi, tôi nhận ra đó là không cần thiết để tham khảo các lớp css hai lần.Tôi cập nhật mã của tôi để chuyển đổi nó thành một plugin jquery, và tạo ra hai giải pháp, tùy thuộc vào những sở thích
Nhận tất cả các hộp kiểm có kiểm tra được loại trừ lẫn nhau
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Nhóm tất cả các kiểm tra loại trừ lẫn nhau hộp trong một phần tử chứa
Javascript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Thưởng thức :-)
Có lý do cụ thể nào bạn không muốn sử dụng các phần tử radio cho điều này không? –
các hộp kiểm cùng loại exe ------ Radiobuttons! – Bazzz
aka Radiobuttons – John