[英]Limit/disable/enable checkbox
我有一个关于此链接的问题: 限制默认选中复选框 。
我扩展了脚本验证的代码,这就是我想要做的。
这是我的示例代码:
var mvp = 5;
$(document).ready(function() {
$("input:checkbox").each(function( index ) {
this.checked = ( index < mvp );
});
$("input:checkbox").click(function() {
var bol = $("input:checkbox:checked").length != mvp;
if(bol){
alert("You have to choose "+ mvp +" mvp's only");
this.checked = false;
$("#button-cart").attr("disabled", true);
}
else{
$("input:checkbox").not(":checked").attr("disabled",bol);
$("#button-cart").attr("disabled", false);
}
});
});
这是小提琴: 小提琴
基于该示例,我将mvp的值设置为5.当页面加载时,检查默认5复选框。 然后,如果您取消选中1,则警报将触发它表示您应该有5个mvp,然后按钮将禁用。 再次选中复选框后,将出现该按钮。 但是有2个左边的复选框,用户可以选择。 但如果用户超过5个选项,则警报将再次触发并将其返回到5个选中的复选框。 这里的问题是按钮将保持禁用状态。
你能帮我做一下这样的逻辑:D提前谢谢..
试试这个,
var mvp = 5;
$(document).ready(function () {
$("input:checkbox").each(function (index) {
this.checked = (index < mvp);
}).click(function () {
en_dis= $("input:checkbox:checked").length < mvp
$('#button-id').prop('disabled', en_dis);
// to disable other checkboxes
$('input:checkbox:checked').length >= mvp &&
$("input:checkbox:not(:checked)").prop('disabled',true);
}).change(function () {
if ($(this).siblings(':checked').length >= mvp) {
this.checked = false;
}
});
});
您不应该设置复选框的checked属性并禁用该按钮。
干得好:
$(function () {
var $button = $('#button-id'),
mvp = 5;
$("input:checkbox").each(function (index) {
this.checked = (index < mvp);
}).on("click", function () {
if ($("input:checkbox:checked").length != mvp) {
alert("You have to choose " + mvp + " mvp's only");
$button.prop("disabled", true);
} else {
$("input:checkbox").not(":checked").prop("disabled", false);
$button.prop("disabled", false);
}
});
});
工作演示: http : //jsfiddle.net/R79cM/
写:
$("input:checkbox").each(function (index) {
this.checked = (index < mvp);
});
$("#button-id").attr("disabled", true);
disable();
$("input:checkbox").change(function () {
var bol = $("input:checkbox:checked").length != mvp;
if (bol) {
alert("You have to choose " + mvp + " mvp's only");
$("#button-id").attr("disabled", true);
enable();
} else {
$("input:checkbox").not(":checked").attr("disabled", bol);
$("#button-id").attr("disabled", false);
disable();
}
});
function enable(){
$("input:checkbox").not(":checked").each(function(){
$(this).removeAttr("disabled");
});
}
function disable(){
$("input:checkbox").not(":checked").each(function(){
$(this).attr("disabled","disabled");
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.