简单的 JavaScript 复选框验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11234622/
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 05:02:21  来源:igfitidea点击:

Simple JavaScript Checkbox Validation

javascripthtmlformsvalidation

提问by TheLettuceMaster

I usually work with PHP so sadly don't have some basic JS principles down. This is all I want to accomplish--I've seen many posts on this topic but they are usually beyond what I need.

我通常使用 PHP,所以遗憾的是没有一些基本的 JS 原则。这就是我想要完成的全部工作——我看过很多关于这个主题的帖子,但它们通常超出了我的需要。

Here is my form:

这是我的表格:

 <input type="checkbox" name="checkbox" value="check"  />
 <input type="submit" name="email_submit" value="submit" onclick="----??----"  />

The checkbox is a simple "I agree". I want the submit button to be pressed and it will only submit if that check box is selected.

复选框是一个简单的“我同意”。我希望提交按钮被按下,并且只有在选中该复选框时才会提交。

Here's the thing: I want the simple, cheating way -- no methods -- just some inline code in that form (assuming its not overly long?). This is not a public page, I just need something quick and simple with that type of validation. If its unchecked, it will throw an alert(); if its checked it will submit via post through php and go on as normal.

事情是这样的:我想要简单的作弊方式——没有方法——只是一些这种形式的内联代码(假设它不是太长?)。这不是一个公共页面,我只需要通过这种类型的验证快速简单地进行一些操作。如果未选中,它会抛出一个 alert(); 如果它被选中,它将通过 php 通过 post 提交并继续正常进行。

回答by PleaseStand

You could use:

你可以使用:

 if(!this.form.checkbox.checked)
{
    alert('You must agree to the terms first.');
    return false;
}

(demo page).

演示页面)。

<input type="checkbox" name="checkbox" value="check"  />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}"  />
  • Returning falsefrom an inline event handler will prevent the default action from taking place (in this case, submitting the form).
  • !is the Boolean NOT operator.
  • thisis the submit button because it is the element the event handler is attached to.
  • .formis the form the submit button is in.
  • .checkboxis the control named "checkbox" in that form.
  • .checkedis true if the checkbox is checked and false if the checkbox is unchecked.
  • false从内联事件处理程序返回将阻止发生默认操作(在这种情况下,提交表单)。
  • !布尔非运算符
  • this是提交按钮,因为它是事件处理程序附加到的元素。
  • .form是提交按钮所在的表单。
  • .checkbox是该表单中名为“复选框”的控件。
  • .checked如果复选框被选中,则为真,如果复选框未选中,则为假。

回答by PrestaShark

For now no jquery or php needed. Use just "required" HTML5 input attrbute like here

现在不需要 jquery 或 php。仅使用“必需的”HTML5 输入属性,例如此处

 <form>
        <p>
            <input class="form-control" type="text" name="email" />
            <input type="submit" value="ok" class="btn btn-success" name="submit" />
            <input type="hidden" name="action" value="0" />
        </p>
        <p><input type="checkbox" required name="terms">I have read and accept <a href="#">SOMETHING Terms and Conditions</a></p>
 </form>

This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.

这将在选择复选框之前验证并阻止任何提交。语言独立的解决方案,因为它是由用户 Web 浏览器生成的。

回答by Eric J.

You can do something like this:

你可以这样做:

<form action="../" onsubmit="return checkCheckBoxes(this);">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
    if (
    theForm.MyCheckbox.checked == false) 
    {
        alert ('You didn\'t choose any of the checkboxes!');
        return false;
    } else {    
        return true;
    }
}
//-->
</script> 

http://lab.artlung.com/validate-checkbox/

http://lab.artlung.com/validate-checkbox/

Although less legible imho, this can be done without a separate function definition like this:

虽然不太清晰,恕我直言,这可以在没有像这样的单独函数定义的情况下完成:

<form action="../" onsubmit="if (this.MyCheckbox.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
    <p><input type="CHECKBOX" name="MyCheckbox" value="This..."> This...</p>
    <p><input type="SUBMIT" value="Submit!"></p>
</form>

回答by tjscience

You can do the following:

您可以执行以下操作:

<form action="/" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('please agree'); return false; }">
    <input type="checkbox" name="checkbox" value="check" id="agree" />
    <input type="submit" name="email_submit" value="submit" />
</form>?

Here is a working demo - http://jsfiddle.net/Ccr2x/

这是一个工作演示 - http://jsfiddle.net/Ccr2x/

回答by siva

var confirm=document.getElementById("confirm").value;
         if((confirm.checked==false)
         {
         alert("plz check the checkbox field");
         document.getElementbyId("confirm").focus();
         return false;
         }

回答by Jordizle

If your checkbox has an ID of 'checkbox':

如果您的复选框的 ID 为“复选框”:

 if(document.getElementById('checkbox').checked == true){ // code here }

HTH

HTH

回答by maxshuty

Another simple way is to create a function and check if the checkbox(es) are checked or not, and disable a button that way using jQuery.

另一种简单的方法是创建一个函数并检查复选框是否被选中,然后使用 jQuery 以这种方式禁用按钮。

HTML:

HTML:

<input type="checkbox" id="myCheckbox" />
<input type="submit" id="myButton" />

JavaScript:

JavaScript:

var alterDisabledState = function () {

var isMyCheckboxChecked = $('#myCheckbox').is(':checked');

     if (isMyCheckboxChecked) {
     $('myButton').removeAttr("disabled");
     } 
     else {
             $('myButton').attr("disabled", "disabled");
     }
}

Now you have a button that is disabled until they select the checkbox, and now you have a better user experience. I would make sure that you still do the server side validation though.

现在您有一个在他们选中复选框之前被禁用的按钮,现在您拥有更好的用户体验。不过,我会确保您仍然进行服务器端验证。

回答by Mahesh

If the check box's ID"Delete" then for the "onclick" event of the submit buttonthe javascript function can be as follows:

如果复选框的 ID 为删除”,那么对于提交按钮的“ onclick”事件,javascript 函数可以如下所示:

html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">

script:
<script type="text/Javascript">
    function deleteData() {
        if(!document.getElementById('Delete').checked){
            alert('Checkbox not checked');
            return false;
        }
</script>

回答by aditya

Another Simple way is to create & invoke the function validate()when the form loads & when submit button is clicked. By using checkedproperty we check whether the checkbox is selected or not. cbox[0]has an index 0which is used to access the first value (i.e Male) with name="gender"

另一种简单的方法是validate()在表单加载和单击提交按钮时创建和调用该函数。通过使用checked属性,我们检查复选框是否被选中。 cbox[0]有一个索引0,用于访问第一个值(即男性)name="gender"

You can do the following:

您可以执行以下操作:

function validate() {
  var cbox = document.forms["myForm"]["gender"];
  if (
    cbox[0].checked == false &&
    cbox[1].checked == false &&
    cbox[2].checked == false
  ) {
    alert("Please Select Gender");
    return false;
  } else {
    alert("Successfully Submited");
    return true;
  }
}
<form onload="return validate()" name="myForm">
  <input type="checkbox" name="gender" value="male"> Male

  <input type="checkbox" name="gender" value="female"> Female

  <input type="checkbox" name="gender" value="other"> Other <br>

  <input type="submit" name="submit" value="Submit" onclick="validate()">
</form>

Demo:CodePen

演示:CodePen

回答by SehrishManzoor

var testCheckbox = document.getElementById("checkbox");  
if (!testCheckbox.checked) {
  alert("Error Message!!");
}
else {
  alert("Success Message!!");
}