我正在创建一个页面,用户将在其中填写由多个表单组成的表单。每种形式都有不同的最大可能答案数。如何最小化代码行数并将这段代码放入循环中?我尝试基于数组进行循环,但我仍然不知道如何在每次循环经过时更改 $("input[name='Pytanie1']")
。我想放入循环中的 JavaScript:
$(document).ready(function () {
$("input[name='Question1']").change(function () {
var maxAllowed = 2;
var cnt = $("input[name='Question1']:checked").length;
if (cnt > maxAllowed) {
$(this).prop("checked", "");
alert('Choose max. ' + maxAllowed + ' answers!');
}
});
});
$(document).ready(function () {
$("input[name='Question2']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='Question2']:checked").length;
if (cnt > maxAllowed) {
$(this).prop("checked", "");
alert('Choose max. ' + maxAllowed + ' answers!');
}
});
});
$(document).ready(function () {
$("input[name='Question3']").change(function () {
var maxAllowed = 3;
var cnt = $("input[name='Question3']:checked").length;
if (cnt > maxAllowed) {
$(this).prop("checked", "");
alert('Choose max. ' + maxAllowed + ' answers!');
}
});
});
感谢您的帮助!
最佳答案
好吧,您可以简单地创建一个最大允许值的数组:
var maxAllowed = [2, 3, 3];
并迭代:
for (var i = 0; i < maxAllowed.length; i++) {
$(document).ready(function () {
var j = i;
$("input[name='Question" + (j + 1) + "']").change(function () {
var cnt = $("input[name='Question" + (j + 1) + "']:checked").length;
if (cnt > maxAllowed[j]) {
$(this).prop("checked", "");
alert('Choose max. ' + maxAllowed[j] + ' answers!');
}
});
});
}
编辑:我之前的代码中似乎存在关闭错误。抱歉
关于javascript - 是否可以将 'number of chosen checkboxes limitation'以多种形式放入循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18204404/