带有要继续的复选框的表单(如果没有显示错误)

时间:2014-03-07 01:12:28

标签: javascript jquery html checkbox required

好吧基本上我有一个表格,我添加了一个复选框(同意服务条款复选框),无论如何我需要做到这一点,以便需要检查以继续捐赠过程...我只有HTML代码我不知道如何使这项工作..如果没有检查我想要一个javascript警告弹出显示错误“你必须同意服务条款”。

继承我的HTML代码

<form method="POST">
<!-- Add ranks with a new value on the next line! -->
<select name="rank">
<option value="1">Donator ($1.20)</option>
<option value="2">Moderator ($5.00)</option>
<option value="3">Administrator ($13.37)</option>
<option value="4">Super-Administrator ($33.00)</option>
</select>
<br />
<br />
<input type="checkbox" name="required">I agree to the <a href="/donate/tos/"> terms of service</a>.<br /><br />
<input type="submit" role="button" type="submit" value="Donate" class="btn btn-danger">
</form>

我很确定这是用javascript完成的,除了我对javascript和amp;的经验非常少。我不知道如何完成这个

3 个答案:

答案 0 :(得分:1)

put this code in your <head> :-
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
    function IsTermChecked() {
        if (!$("input:checkbox").is(":checked")) {
            alert("You must agree to the terms of service.");
            return false;
        }
        else
            return true;
    }

</script>
</head>
Also call the function IsTermChecked() on submit click :-

<input type="submit" role="button" value="Donate" class="btn btn-danger" onclick="return IsTermChecked();">

 You have to use jquery library to user jQuery's functions. Try this. This will work definitely.

答案 1 :(得分:0)

您可以禁用提交按钮,然后在选中复选框时启用它:

<强> HTML

<form method="POST">
<!-- Add ranks with a new value on the next line! -->
<select name="rank">
<option value="1">Donator ($1.20)</option>
<option value="2">Moderator ($5.00)</option>
<option value="3">Administrator ($13.37)</option>
<option value="4">Super-Administrator ($33.00)</option>
</select>
<input type="checkbox" name="required">I agree to the <a href="/donate/tos/">terms of service</a>.<br />
<input type="submit" disabled role="button" type="submit" value="Donate" class="btn btn-danger">
</form>

<强>的Javascript

$("input[name='required']").click(function(){
   $("input[type='submit']").prop("disabled", !this.checked);
});

JS小提琴: http://jsfiddle.net/Q2kft/2/

要显示警报,请使用以下命令:

$("input[type='submit']").click(function(e){
    if($("input[name='required']:checked").length == 0){
       e.preventDefault();
       alert("You must check the input");
    }
});

JS小提琴: http://jsfiddle.net/Q2kft/1/

答案 2 :(得分:0)

$(document).ready(function() {
    $("form").submit(function() {
        if (!$(this).find(":checkbox[name=required]").is(":checked")) {
            alert ("You must agree to the terms of service.");
            return false;
        }
    });
});