【问题标题】:how i can validate checkbox with javascript?我如何使用 javascript 验证复选框?
【发布时间】:2018-06-07 18:08:28
【问题描述】:

我是 Java 脚本的新手。 我想用复选框类型验证输入。 我使用下面的代码进行验证。

<form onsubmit="return checkForm(this);">
    
    <input type="checkbox" name="terms" value="accept" id="accept" />
    
</form>

    
            function checkForm(form) {
                alert('hello');
                if (form.terms!=check) {
                    alert("Please indicate that you accept the Terms and Conditions");
                    form.terms.focus();
                    return false;
                }
                return true;
            }
    
 <form name="form1" id="form1" runat="server" onsubmit="return checkForm(this);">
 
<input class="farsi-font" type="checkbox" name="terms" value="accept" id="accept" style="color: #000" runat="server" />

 </form>

但是我收到警报(“请表明您接受条款和条件”);“表单将发布到数据库。验证只是提醒用户并且不会阻止表单发布。任何机构都可以帮助我吗? 谢谢

【问题讨论】:

  • 请注意,您可以根据需要标记输入,包括复选框输入。另请注意,使用 HTML 处理程序属性(例如onsubmit)会导致痛苦、痛苦、痛苦。在 JavaScript 中使用 .addEventListener
  • @JaredSmith 感谢您的解决方案,很有帮助
  • 我很高兴它有帮助。请接受我的回答(下面我的回答旁边的绿色复选标记)。

标签: javascript validation


【解决方案1】:

不确定该代码的来源,但我会这样做:

<input type="checkbox" name="terms" value="accept" id="accept" required />

注意添加必需的属性。

document.querySelector('#accept').setCustomValidity('Please accept the terms and conditions');

现在,当用户提交表单时,如果未选中该框,它将显示您的消息,表单将不会提交。您可以通过在提交处理程序中放置 console.logdebugger 语句来测试:

// Note that as I said in the comments, attaching the handler
// this way is preferable to using the onsubmit HTML attribute.
document.querySelector('#form1').addEventListener('submit', function(evt) {
  console.log('stop the presses!');
});

【讨论】:

    【解决方案2】:

    试试这个:

    HTML

    <form onsubmit="return checkForm(event, this);">
      <input type="checkbox" name="terms" id="accept" />
    </form>
    

    JS

    function checkForm(event, form) {
      event.preventDefault();
      if (!form.terms.checked) {
        alert("Please indicate that you accept the Terms and Conditions");
        return false;
      }
      return true;
    }
    

    编辑:

    如果只使用html提交表单,可以有以下几种方式。

    在表单中输入

    <form onsubmit="return checkForm(event, this);">
      <input type="checkbox" name="terms" id="accept" />
      <input type="submit" value="Submit the form" />
    </form>
    

    在它外面有一个按钮。 (现在表单必须有一个 id)

    <form id="myForm" onsubmit="return checkForm(event, this);">
      <input type="checkbox" name="terms" id="accept" />
    </form>
    <button type="submit" form="myForm">Submit the form</button>
    

    【讨论】:

    • 亲爱的 Alyson,当我使用你建议的代码时,提交按钮不起作用,你知道这个问题吗?
    • 提交按钮是&lt;input type="submit" value="Submit the form" /&gt; 还是类似的?我将通过更多有关如何提交表单的示例来编辑答案。
    猜你喜欢
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2017-09-05
    • 2011-01-15
    • 1970-01-01
    • 2012-05-13
    相关资源
    最近更新 更多