所选项目为5个时,如何禁用其余的复选框?我在想,在jquery中可能有一种方法可以做到这一点。下面是我的代码。
<table>
@{ var i = 0;}
@foreach (var testimonials in Model.Testimonials)
{
<tr>
<td style="padding: 2px 0 2px 2px;">
@Html.CheckBox("Testimonials[" + i.ToString() + "].DisplayTestimonials", testimonials.DisplayTestimonials.Value, new { @class = "chkItems" })
@Html.Hidden("Testimonials[" + i.ToString() + "].ResponseId", testimonials.ResponseId.ToString())
</td>
<td style="padding: 2px 0 2px 2px;">@Html.TextBox("Testimonials[" + i.ToString() + "].FirstName", testimonials.FirstName, new { @readonly = "readonly", @class = "TextBoxAsLabel" })</td>
<td style="padding: 2px 0 2px 2px;">@Html.TextBox("Testimonials[" + i.ToString() + "].LastName", testimonials.LastName, new { @readonly = "readonly", @class = "TextBoxAsLabel" })</td>
<td style="padding: 2px 0 2px 2px;">@Html.TextBox("Testimonials[" + i.ToString() + "].Question5Answer", testimonials.Question5Answer.ToString(), new { @readonly = "readonly", @class = "TextBoxAsLabel" })</td>
</tr>
i++;
}
解决方案:
<script type="text/javascript">
$(document).ready(function () {
function countchecked() {
var n = $("input:checked").length;
if (n >= 5)
$('.chkItems:not(:checked)').attr("disabled", "disabled");
else
$('.chkItems:not(:checked)').removeAttr("disabled");
}
$(":checkbox").click(countchecked);
});
发布于 2011-02-25 22:40:00
以下是我提出的解决方案:
var checkedcount=0;
$("input.chkItems").change(function(){
if(this.checked) checkedcount++; else checkedcount--;
if(checkedcount>=5) $("input.chkItems:not(:checked)").attr("disabled", "disabled");
else $("input.chkItems:not(:checked)").removeAttr("disabled");
});工作演示:http://jsbin.com/etici4
已编辑:按建议将事件更改为"onchange“
发布于 2011-02-25 22:34:18
下面是一个示例(按照建议进行了改进)。您可能想要优化选择器。
<script type="text/javascript">
jQuery(function() {
jQuery("input:checkbox.chkItems").change(
function() {
var p = $(this).parent();
var e = p.find("input:checked").length >= 5;
p.find("input:not(:checked)").attr('disabled', e ? 'disabled' : '');
}
);
});
</script>
<div id="checkbox-group">
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
<input type="checkbox" class="chkItems" />
</div>发布于 2011-02-25 22:32:18
我在想,也许可以做一个数组来跟踪选中框的数量,比如enabled=false if(array.length==5 && self!= checked )
如果你写一点javascript,这可能行得通。我对jQuery还不够熟悉,不知道是否有一些简单的内置方法可以做到这一点
https://stackoverflow.com/questions/5118296
复制相似问题