Javascript 确保至少选中一个复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11787665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:05:18  来源:igfitidea点击:

Making sure at least one checkbox is checked

javascripthtmlcheckbox

提问by MegaSly

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.

我有一个带有多个复选框的表单,我想使用 JavaScript 来确保至少选中一个。这就是我现在所拥有的,但无论选择什么,都会弹出警报。

JS (wrong)

JS(错误)

function valthis(){
 if (document.FC.c1.checked) {
   alert ("thank you for checking a checkbox")
  } else  {
   alert ("please check a checkbox")
  }
}

HTML

HTML

<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1 
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br> 
<input type = "checkbox" name = "c1" value = "c4"/> C4 
<br>
</form>
<br>
<br>

<input type = "button" value = "Edit and Report" onClick = "valthisform();">

So what I ended up doing in JS was this:

所以我最终在 JS 中做的是这样的:

function valthisform(){
 var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked

 if (chkd == true){

 } else {
    alert ("please check a checkbox")
 }

}

I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.

我决定放弃“谢谢”部分以适应作业的其余部分。非常感谢,每个人的建议真的很有帮助。

回答by mash

You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1how will the browser know which you are referring to?

如果您打算像document.FC.c1. 如果您有多个名为的复选框c1,浏览器如何知道您指的是哪个?

Here's a non-jQuery solution to check if any checkboxes on the page are checked.

这是一个非 jQuery 解决方案,用于检查页面上是否有任何复选框被选中。

var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);

You need the Array.prototype.slice.callpart to convert the NodeListreturned by document.querySelectorAllinto an array that you can call someon.

您需要Array.prototype.slice.callNodeList返回的部分转换为document.querySelectorAll您可以调用的数组some

回答by Mageek

This should work:

这应该有效:

function valthisform()
{
    var checkboxs=document.getElementsByName("c1");
    var okay=false;
    for(var i=0,l=checkboxs.length;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
            break;
        }
    }
    if(okay)alert("Thank you for checking a checkbox");
    else alert("Please check a checkbox");
}

If you have a question about the code, just comment.

如果您对代码有疑问,请发表评论。



I use l=checkboxs.lengthto improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/

l=checkboxs.length用来提高性能。请参阅http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/

回答by Temp

Check this.

检查这个。

You can't access form inputs via their name. Use document.getElementsmethods instead.

您无法通过名称访问表单输入。改用document.getElements方法。

回答by Kyle Vassella

Vanilla JS:

香草JS:

var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable

function activitiesReset() {
    var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                return true;
            }
        }
        return false;
    }
    error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead. 
        if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
            error[2].style.display = 'block'; // red error label is now visible.
        }
}

for (var i=0; i<checkboxes.length; i++) {  // whenever a checkbox is checked or unchecked, activitiesReset runs.
    checkboxes[i].addEventListener('change', activitiesReset);
}


Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchangeevent (written as .addEventListener('change', function(){});


说明:
一旦尝试提交表单,这将更新您的复选框部分的标签,以通知用户如果他/她尚未选中复选框。如果未选中复选框,则会显示隐藏的“错误”标签,提示用户“请选中复选框!”。如果用户选中至少一个复选框,红色标签会立即再次隐藏,显示原始标签。如果用户再次取消选中所有复选框,红色标签会实时返回。这是通过 JavaScript 的onchange事件(写成.addEventListener('change', function(){});

回答by Parth Patel

You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.

您可以使用这个简单的代码检查是否至少选中了一个复选框。您也可以删除您的消息。

Reference Link

参考链接

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>

回答by Nitika Chopra

if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
            || ($("#checkboxid3").is(":checked"))) {
 //Your Code here
}

You can use this code to verify that checkbox is checked at least one.

您可以使用此代码来验证复选框是否至少被选中。

Thanks!!

谢谢!!

回答by Arthur van Acker

I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them. Let's begin with giving the checkboxes a class so we can round them up very nicely. I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.

我会选择更实用的方法。自 ES6 以来,我们已经获得了如此出色的工具来解决我们的问题,那么为什么不使用它们呢?让我们从给复选框一个类开始,这样我们就可以很好地将它们围起来。我更喜欢使用类而不是 input[type="checkbox"] 因为现在该解决方案更通用,并且当您的文档中有更多复选框组时也可以使用。

HTML

HTML

    <input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
    <input type="checkbox" class="checkbox" value=ck2 /> ck2<br />

JavaScript

JavaScript

function atLeastOneCheckboxIsChecked(){
    const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
    return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}

When called, the function will return false if no checkbox has been checked and true if one or both is.

调用时,如果没有选中复选框,则该函数将返回 false;如果选中一个或两个复选框,则返回 true。

It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true. the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.

它的工作原理如下,reducer 函数有两个参数,累加器 (acc) 和当前值 (curr)。对于数组上的每次迭代,如果累加器或当前值为真,则reducer 将返回真。前一次迭代的返回值是当前迭代的累加器,因此,如果它为真,它将一直保持为真直到结束。

回答by crashtestxxx

Prevent user from deselecting last checked checkbox.
jQuery (original answer).

防止用户取消选择上次选中的复选框。
jQuery(原始答案)。

$('input[type="checkbox"][name="chkBx"]').on('change',function(){
    var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
        return this.value;
    }).toArray();

    if(getArrVal.length){
        //execute the code
        $('#msg').html(getArrVal.toString());

    } else {
        $(this).prop("checked",true);
        $('#msg').html("At least one value must be checked!");
        return false;

    }
});

UPDATED ANSWER 2019-05-31
Plain JS

更新答案 2019-05-31 纯
JS

let i,
    el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
    msg = document.getElementById('msg'),
    onChange = function(ev){
        ev.preventDefault();
        let _this = this,
            arrVal = Array.prototype.slice.call(
                document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
                    .map(function(cur){return cur.value});

        if(arrVal.length){
            msg.innerHTML = JSON.stringify(arrVal);
        } else {
            _this.checked=true;
            msg.innerHTML = "At least one value must be checked!";
        }
    };

for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>

回答by saira

< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" >  <  / script >
     < script type = "text/javascript" >

function checkSelectedAtleastOne(clsName) {
    if (selectedValue == "select")
        return false;

    var i = 0;
    $("." + clsName).each(function () {

        if ($(this).is(':checked')) {
            i = 1;
        }

    });

    if (i == 0) {
        alert("Please select atleast one users");
        return false;
    } else if (i == 1) {
        return true;
    }

    return true;

}

$(document).ready(function () {
    $('#chkSearchAll').click(function () {

        var checked = $(this).is(':checked');
        $('.clsChkSearch').each(function () {
            var checkBox = $(this);
            if (checked) {
                checkBox.prop('checked', true);
            } else {
                checkBox.prop('checked', false);
            }
        });

    });

    //for select and deselect 'select all' check box when clicking individual check boxes
    $(".clsChkSearch").click(function () {

        var i = 0;
        $(".clsChkSearch").each(function () {

            if ($(this).is(':checked')) {}
            else {

                i = 1; //unchecked
            }

        });

        if (i == 0) {
            $("#chkSearchAll").attr("checked", true)
        } else if (i == 1) {

            $("#chkSearchAll").attr("checked", false)
        }

    });

});

<  / script >