【问题标题】:When form is submitted, validate html checkbox and display javascript alert if it is not checked提交表单时,验证 html 复选框并在未选中时显示 javascript 警报
【发布时间】:2015-07-13 18:13:52
【问题描述】:

我正在尝试使用 jQuery 和可能的 jQuery 验证插件来验证 HTML 中的表单。我想要发生的是当按下提交按钮时,它应该验证是否选中了某个 HTML 复选框。如果没有检查,我想发出一个 javascript 警报错误,说它没有检查。否则表格应该正常提交。我正在尝试将其集成到使用 Contact Form 7 插件创建的 WordPress 表单中。

我已按要求添加了我的代码。

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 

    <script> 
        // wait for the DOM to be loaded 
        $(document).ready(function() { 
            // bind 'myForm' and provide a simple callback function 
            $('#myForm').ajaxForm(function() { 
                alert("Thank you for your comment!"); 
            }); 
        }); 
    </script> 
</head>
<body>
<form id="myForm" action="action.php" method="post"> 
<input type="checkbox" name="tos" value="Agreed to TOS" id="confirm">
<input type="submit" value="Submit Comment" /> 
</form>
</body>
</html>

没有太多,但我正在尝试使用 jquery 验证。只使用 javascript 可能很简单。

【问题讨论】:

  • 你的问题是什么?
  • 在联系表格 7 中,可以选择是否需要验证复选框。您只需要在创建表单元素时选中 require 复选框。
  • 我已经更新了代码。只需验证 HTML 复选框。

标签: jquery wordpress validation contact-form-7


【解决方案1】:

如果

<input id="submit" type ="submit" name ="submit" />

是表单中的提交按钮,添加onclick

<input id="submit" type ="submit" name ="submit" oncLick = "return validate();">

您的验证应如下所示:

function validate(){
  if your checkbox is set
       return true;
  else
       return false;
}

如果您的 validate 函数返回 true,则只会提交您的表单。

【讨论】:

    【解决方案2】:
    var atleast = 1;
    function validate() {
        debugger;
        var CHK = document.getElementById("<%=chk1");
        var checkbox = document.getElementsByTagName("input");
        var counter = 0;
        for (var i = 0; i < checkbox.length; i++) {
            if (checkbox[i].checked) {
                counter++;
            }
        }
        if (atleast > counter) {
            alert("Please select atleast " + atleast + " employee ");
            return false;
        }
        return true;
    }
    

    //给

    enter code here 
    

    用于演示

    http://design.ionxindia.com/Manager/AttendanceRequest

    【讨论】:

    • 您的演示无法正常工作,它显示了一个登录屏幕。此外,最好使用 Stack Snippet 来演示它。
    猜你喜欢
    • 2023-02-17
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2019-08-24
    • 2014-04-13
    • 2015-11-21
    • 1970-01-01
    相关资源
    最近更新 更多