I am validating some check boxes and would like for the user to be able to select only 4 (from 7 possible) and disable the others if the current box is being checked(if there are already 3 checked) or enable the everything if the current box is being unchecked. I'm really not sure where's the problem. This is my first experience with JavaScript...
我正在验证一些复选框,并希望用户能够仅选择4(从7可能)并禁用其他如果正在检查当前框(如果已经检查3)或启用当前的所有内容框未经检查。我真的不确定问题出在哪里。这是我第一次使用JavaScript ...
function verify_selected(selected_check_box_id) {
var count = 0;
var selected_check_boxes = new Array();
var check_boxes = new Array();
var inputs = document.getElementsByTagName("input");
for( var i in inputs ) {
if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] );
}
// get current checkbox
for( var i in check_boxes ) if( check_boxes[i].id == selected_check_box_id ) var current_check_box = check_boxes[i];
var current_check_box_is_checked = current_check_box.checked;
// get all "checked"
for( var i in check_boxes ) {
if( check_boxes[i].checked ) {
selected_check_boxes.push( check_boxes[i] );
count += 1;
}
}
if( current_check_box_is_checked ) {
// checking
if( count < 4 ) {
current_check_box.checked = true;
// count = 4 - disabling
if( count == 4 ) {
for( var i in check_boxes ) {
if( !check_boxes[i].checked ) check_boxes[i].disabled = true;
}
}
}
else current_check_box.checked = false;
} else {
// unchecking
// count is < 4 -> enabling
for( var i in check_boxes ) {
check_boxes[i].disabled = false;
}
}
}
Any help is welcome, thanks in advance.
欢迎任何帮助,提前谢谢。
3 个解决方案
#1
There were a couple of things wrong. Lets give the good version first.
有几件事是错的。让我们先给出好的版本。
I also put up a demo at: http://jsbin.com/ajimi
我还在http://jsbin.com/ajimi上放了一个演示
function verify_selected(currentCheckbox) {
var count = 0;
var selected_check_boxes = []; // this will be fine...
var check_boxes [];
var inputs = document.getElementsByTagName("input");
for( var i in inputs ) {
if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] );
}
// get all "checked"
for( var i in check_boxes ) {
if( check_boxes[i].checked ) {
count += 1;
}
}
if( currentCheckbox.checked && (count == 4)) {
for( var i in check_boxes )
if( !check_boxes[i].checked )
check_boxes[i].disabled = true;
} else {
for( var i in check_boxes )
check_boxes[i].disabled = false;
}
}
In the original version, you've got a piece of code which looked like:
在原始版本中,您有一段代码看起来像:
if (count < 4) {
if (count == 4) {
Not gonna happen. So, that was corrected.
不会发生。所以,这已得到纠正。
As you saw also in another answer, we changed the function to take out looking for an ID. Rather than figuring out the ID in some separate function (I assume you're tracking the "last clicked" by some other function which occurs), just use the this modifier to pass it into the function.
正如您在另一个答案中看到的那样,我们更改了函数以寻找ID。而不是在某个单独的函数中计算ID(我假设您正在跟踪发生的其他函数的“最后点击”),只需使用this修饰符将其传递给函数。
Alright, last but not least, what this would look like in jQuery. Hopefully this will help a little as to understanding how it works and why it's worth using:
好吧,最后但并非最不重要的是,这在jQuery中会是什么样子。希望这有助于了解它的工作原理以及为什么值得使用:
(see example: http://jsbin.com/ihone)
(见例子:http://jsbin.com/ihone)
function limitSelected(e) {
// get all of your checkboxes
var checkBoxes = $(e.currentTarget).parent().children().filter('input:checkbox');
// get the number of checkboxes checked, if 4, we'll disable
var disableCheckBoxes = (checkBoxes.filter(':checked').length == 4);
// enable checkboxes if we have < 4, disable if 4
checkBoxes.filter(':not(:checked)').each(function() {
this.disabled = disableCheckBoxes;
});
}
// when the document is ready, setup checkboxes to limit selection count
// if you have a particular div in which these checkboxes reside, you should
// change the selector ("input:checkbox"), to ("#yourDiv input:checkbox")
$(function() {
$('input:checkbox').click(limitSelected);
});
The other thing I will note about this version is that it works on the group of checkboxes within a div, as opposed to your version which will pick up checkboxes on the entire page. (which is limiting.
关于这个版本,我要注意的另一件事是,它适用于div中的复选框组,而不是你的版本将在整个页面上选中复选框。 (这是限制性的。
#2
From a brief skim, your code seems much too complex for the task.
从简短的浏览中,您的代码对于任务而言似乎过于复杂。
Can I suggest using something like jquery? You can quite easily select the relevant check boxes using the psudeo-selector ':checked'. Also, have a look at this check box tutorial.
我可以建议使用像jquery这样的东西吗?您可以使用psudeo-selector':checked'轻松选择相关的复选框。另外,看看这个复选框教程。
If you don't want to use a library, I'd suggest first creating a function that can count the number of checked check boxes. Then create a function that can disable or enable all unchecked check boxes. Finally, combine the two, and register a function to trigger on the click event for the check boxes.
如果您不想使用库,我建议首先创建一个可以计算已选中复选框数的函数。然后创建一个可以禁用或启用所有未选中复选框的功能。最后,将两者结合起来,并注册一个函数来触发复选框的click事件。
#3
As cofiem
said, your code looks rather complex for what you want to achieve; I recommend breaking it down into a few, smaller functions, to re-use code and make less complex.
正如cofiem所说,你的代码对你想要实现的东西看起来相当复杂;我建议将其分解为几个较小的函数,以重用代码并减少复杂性。
First, implement a function to get all of the checkboxes on the page:
首先,实现一个函数来获取页面上的所有复选框:
function getCheckboxes()
{
var inputs = document.getElementsByTagName("input");
var checkboxes = new Array();
for(var i=0;i<inputs.length;++i) {
if(inputs[i].type=="checkbox")
checkboxes.push(inputs[i]);
}
return checkboxes;
}
Then a function to enable/disable the checkboxes:
然后是一个启用/禁用复选框的功能:
function setDisabled(state) {
var checkboxes = getCheckboxes();
for(i=0;i<checkboxes.length;++i) {
//Only unchecked checkboxes will need to be enabled/disabled
if(!checkboxes[i].checked)
checkboxes[i].disabled = state;
}
}
Now implement your function to verify whether the checkboxes need to be enabled or disabled:
现在实现您的函数以验证是否需要启用或禁用复选框:
function verify_selected(checkbox) {
var checkboxes = getCheckboxes();
var count=0;
for(i=0;i<checkboxes.length;++i) {
if(checkboxes[i].checked)
count++;
}
if(count>=4)
setDisabled(true);
else
setDisabled(false);
}
I have changed your function declaration to pass the actual checkbox object rather than an identifier string; this is much easier to call the function:
我已经更改了函数声明以传递实际的checkbox对象而不是标识符字符串;调用函数要容易得多:
<input type="checkbox" onClick="verify_selected(this);">
//Insert 7 of these..
As you can see the code is much easier to read and maintain, and it is much less complex.
正如您所看到的,代码更易于阅读和维护,而且复杂程度要低得多。
#1
There were a couple of things wrong. Lets give the good version first.
有几件事是错的。让我们先给出好的版本。
I also put up a demo at: http://jsbin.com/ajimi
我还在http://jsbin.com/ajimi上放了一个演示
function verify_selected(currentCheckbox) {
var count = 0;
var selected_check_boxes = []; // this will be fine...
var check_boxes [];
var inputs = document.getElementsByTagName("input");
for( var i in inputs ) {
if( inputs[i].type == "checkbox" ) check_boxes.push( inputs[i] );
}
// get all "checked"
for( var i in check_boxes ) {
if( check_boxes[i].checked ) {
count += 1;
}
}
if( currentCheckbox.checked && (count == 4)) {
for( var i in check_boxes )
if( !check_boxes[i].checked )
check_boxes[i].disabled = true;
} else {
for( var i in check_boxes )
check_boxes[i].disabled = false;
}
}
In the original version, you've got a piece of code which looked like:
在原始版本中,您有一段代码看起来像:
if (count < 4) {
if (count == 4) {
Not gonna happen. So, that was corrected.
不会发生。所以,这已得到纠正。
As you saw also in another answer, we changed the function to take out looking for an ID. Rather than figuring out the ID in some separate function (I assume you're tracking the "last clicked" by some other function which occurs), just use the this modifier to pass it into the function.
正如您在另一个答案中看到的那样,我们更改了函数以寻找ID。而不是在某个单独的函数中计算ID(我假设您正在跟踪发生的其他函数的“最后点击”),只需使用this修饰符将其传递给函数。
Alright, last but not least, what this would look like in jQuery. Hopefully this will help a little as to understanding how it works and why it's worth using:
好吧,最后但并非最不重要的是,这在jQuery中会是什么样子。希望这有助于了解它的工作原理以及为什么值得使用:
(see example: http://jsbin.com/ihone)
(见例子:http://jsbin.com/ihone)
function limitSelected(e) {
// get all of your checkboxes
var checkBoxes = $(e.currentTarget).parent().children().filter('input:checkbox');
// get the number of checkboxes checked, if 4, we'll disable
var disableCheckBoxes = (checkBoxes.filter(':checked').length == 4);
// enable checkboxes if we have < 4, disable if 4
checkBoxes.filter(':not(:checked)').each(function() {
this.disabled = disableCheckBoxes;
});
}
// when the document is ready, setup checkboxes to limit selection count
// if you have a particular div in which these checkboxes reside, you should
// change the selector ("input:checkbox"), to ("#yourDiv input:checkbox")
$(function() {
$('input:checkbox').click(limitSelected);
});
The other thing I will note about this version is that it works on the group of checkboxes within a div, as opposed to your version which will pick up checkboxes on the entire page. (which is limiting.
关于这个版本,我要注意的另一件事是,它适用于div中的复选框组,而不是你的版本将在整个页面上选中复选框。 (这是限制性的。
#2
From a brief skim, your code seems much too complex for the task.
从简短的浏览中,您的代码对于任务而言似乎过于复杂。
Can I suggest using something like jquery? You can quite easily select the relevant check boxes using the psudeo-selector ':checked'. Also, have a look at this check box tutorial.
我可以建议使用像jquery这样的东西吗?您可以使用psudeo-selector':checked'轻松选择相关的复选框。另外,看看这个复选框教程。
If you don't want to use a library, I'd suggest first creating a function that can count the number of checked check boxes. Then create a function that can disable or enable all unchecked check boxes. Finally, combine the two, and register a function to trigger on the click event for the check boxes.
如果您不想使用库,我建议首先创建一个可以计算已选中复选框数的函数。然后创建一个可以禁用或启用所有未选中复选框的功能。最后,将两者结合起来,并注册一个函数来触发复选框的click事件。
#3
As cofiem
said, your code looks rather complex for what you want to achieve; I recommend breaking it down into a few, smaller functions, to re-use code and make less complex.
正如cofiem所说,你的代码对你想要实现的东西看起来相当复杂;我建议将其分解为几个较小的函数,以重用代码并减少复杂性。
First, implement a function to get all of the checkboxes on the page:
首先,实现一个函数来获取页面上的所有复选框:
function getCheckboxes()
{
var inputs = document.getElementsByTagName("input");
var checkboxes = new Array();
for(var i=0;i<inputs.length;++i) {
if(inputs[i].type=="checkbox")
checkboxes.push(inputs[i]);
}
return checkboxes;
}
Then a function to enable/disable the checkboxes:
然后是一个启用/禁用复选框的功能:
function setDisabled(state) {
var checkboxes = getCheckboxes();
for(i=0;i<checkboxes.length;++i) {
//Only unchecked checkboxes will need to be enabled/disabled
if(!checkboxes[i].checked)
checkboxes[i].disabled = state;
}
}
Now implement your function to verify whether the checkboxes need to be enabled or disabled:
现在实现您的函数以验证是否需要启用或禁用复选框:
function verify_selected(checkbox) {
var checkboxes = getCheckboxes();
var count=0;
for(i=0;i<checkboxes.length;++i) {
if(checkboxes[i].checked)
count++;
}
if(count>=4)
setDisabled(true);
else
setDisabled(false);
}
I have changed your function declaration to pass the actual checkbox object rather than an identifier string; this is much easier to call the function:
我已经更改了函数声明以传递实际的checkbox对象而不是标识符字符串;调用函数要容易得多:
<input type="checkbox" onClick="verify_selected(this);">
//Insert 7 of these..
As you can see the code is much easier to read and maintain, and it is much less complex.
正如您所看到的,代码更易于阅读和维护,而且复杂程度要低得多。