所以,我做的第一件事是将 checkbox
的所有实例替换为 'radio
' 仍然没有达到我的效果..我想保留这个 jQuery 脚本允许的“复选标记”和自定义框背景等,一切都很完美,我只需要确保只能检查/选择一个项目..
第一,jQuery..
/*! custom-checkbox - v1.0.1 */
(function ($) {
$.fn.customCheckbox = function() {
return this.each( function(i,v) {
//Ensure that a checkbox element was passed
if ( !$(v).is(':checkbox') ) {
return false;
}
//Add classes
$(v).addClass("custom-checkbox");
//If not wrapped within label tags, wrap it
var parentLabel = $(v).parent("label");
var withinLabel = parentLabel.length;
if ( !withinLabel ){
$(v).wrap("<label class='custom-checkbox-label'></label>");
}
else {
parentLabel.addClass('custom-checkbox-label');
}
//Create dummy checkbox
var dummy = $("<span class='custom-checkbox-display'></span>");
$(v).after(dummy);
if ( $(v).prop("checked") ) {
$(v).next('.custom-checkbox-display').addClass("checked");
}
//Add/remove classes to checkbox whenever state changes
$(v).change( function(e) {
var checkbox = $(e.currentTarget);
var state = checkbox.prop("checked");
if ( state ) {
dummy.addClass("checked");
}
else {
dummy.removeClass("checked");
}
});
//Make reset button aware of the custom checkboxes
var form = $(v).parents("form");
var reset = form.find("input[type='reset']");
reset.each( function(ri,rv) {
if ( !$(rv).hasClass("custom-checkbox-aware") ) {
$(rv).addClass("custom-checkbox-aware");
$(rv).click( function() {
form.find(".custom-checkbox:checked").trigger("click");
});
}
});
});
};
}(jQuery));
html 表单标记...
<div class="form-group_district">
<p class="label">District Name*</p><br>
<label class="labeldistrict">
<input type="checkbox" name="NYCDistrictName" class="checkboxed" required >
I teach in the New York City Department of Education</label><br>
<label class="labeldistrict">
<input type="checkbox" name="ChiDistrictName" class="checkboxed" required >
I teach in the Chicago Public Schools</label><br>
<label class="labeldistrict">
<input type="checkbox" name="LADistrictName" class="checkboxed" required >
I teach in the Los Angeles Unified School District</label><br>
<label class="labeldistrict">
<input type="checkbox" name="othDistrictName" class="checkboxed" required >
Other</label><br>
<input type="text" name="othDistrictName" maxlength="100" class="otherdistrict" required ><br>
<br>
</div>
对于 fiddle 手来说..这是一个简单的演示。想象一下“检查标记”图像在选择/焦点上显示。 (我真的不想保存它们并将它们托管在本演示的某个地方)。
最佳答案
您可以重置所有其他元素,而不是检查当前元素,例如:
//Add/remove classes to checkbox whenever state changes
$(v).change( function(e) {
$('input[type="checkbox"].custom-checkbox:checked').not(v).prop("checked", false);
$('.custom-checkbox-display.checked').not(dummy).removeClass("checked");
var checkbox = $(e.currentTarget);
var state = checkbox.prop("checked");
if ( state ) {
dummy.addClass("checked");
}
else {
dummy.removeClass("checked");
}
});
关于javascript - 自定义 jQuery 复选框只允许一项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654046/