【问题标题】:jquery do not submit form until checkbox is tickedjquery在勾选复选框之前不提交表单
【发布时间】:2014-05-15 14:02:14
【问题描述】:

您好,我已经插入了一些 jquery 来验证某个表单上的复选框,我在 jsFIddle 上做了一个简单的示例,但是如果未单击复选框,表单仍会提交,但警报仍然存在显示。

如果未勾选复选框,我如何停止提交?我的代码在下面或查看我的jsFIddle

$(document).ready(function () {

var check;

$("#test-with-prop").on("click", function () {
    if ($("input[id=test]").is(":checked")) {
        check = $("#mycheckbox").prop("checked");
        if (!check) {
            alert("Please confirm that you have read and understood the charging agreement between yourself, and .");
        } 
    }
});
});

【问题讨论】:

  • 在 OP 中显示相关的 HTML 标记。
  • 这与您上一个问题有何不同?

标签: javascript jquery html forms validation


【解决方案1】:

您应该按照here 的描述使用 $.on('submit')。

例如:

$(document).ready(function () {
    var $form = $('#form-id');
    var $checkbox = $('#mycheckbox');

    $form.on('submit', function(e) {
        if(!$checkbox.is(':checked')) {
            alert('Please confirm!');
            e.preventDefault();
        }
    });
});

这是working example

【讨论】:

  • 你自己测试过吗?无论我做什么,我都会不断收到“请确认”。
【解决方案2】:
$('#test-with-prop').click(function () {
            if ($('#mycheckbox').is(":checked")) {
                return true;
            }
            else {
                alert("Checkbox is not selected");
                return false;
            }
        });

【讨论】:

    【解决方案3】:

    只添加e.preventDefault();并取消提交:

     // Example 3 - With jQuery prop  
        $("#test-with-prop").on("click", function (e) {
            if ($("input[id=test]").is(":checked")) {
                check = $("#mycheckbox").prop("checked");
                if (!check) {
                    alert("Please confirm");
                    e.preventDefault(); // add this line
                } 
            }
        });
    

    【讨论】:

    • e.preventDefault();
    • 更好地使用e.preventDefault();return false; 也会调用e.stopPropagation();,虽然它可能适合这种情况,但使用e.preventDefault() 是一个好习惯。
    【解决方案4】:

    你可以试试这个。并使用 a 作为 Inputtype a Button 而不是 type="submit"....

    $("#test-with-prop").on("click", function () {
            if ($("input[id=test]").is(":checked")) {
                check = $("#mycheckbox").prop("checked");
                if (!check) {
                    alert("Please confirm that you have read and understood the charging agreement between ");
                } else{
                    $("#form").submit();
                }
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多