如果未选中复选框,则阻止表单提交

sus*_*oek 3 javascript forms ajax checkbox jquery

如果输入字段为空,我正在使用一些Ajax/Javascript来阻止表单提交.

$(function() {

    var form = $('#contact-form-edc');

    $(form).submit(function(e) {
        e.preventDefault();


        var formData = $(form).serialize();

  if (document.getElementById("nachricht-field").value.length < 10) {
    document.getElementById('error-nachricht').style.display = "";
  } else {

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })

        .done(function(response) {
         document.getElementById('success').style.display = "";
          document.getElementById('error').style.display = "none";
      document.getElementById('error-nachricht').style.display = "none";

            $('input').val('');
   $('textarea').val('');
   $('.button').val('Abschicken');
   $('input[name=datenschutz]').attr('checked', false);
        })
        .fail(function(data) {
           document.getElementById('error').style.display = "";
            document.getElementById('success').style.display ="none";
        });

  }

    });

});
Run Code Online (Sandbox Code Playgroud)

该脚本工作正常但不记下表单的复选框.复选框

<input type="checkbox" name="datenschutz" value="Datenschutz" required="required" >
Run Code Online (Sandbox Code Playgroud)

也是必需的,但用户可以在不选中复选框的情况下提交表单.是否有一个小脚本可以在当前的Ajax脚本中实现?

Pra*_*man 7

使用这种方式:

$(form).submit(function(e) {
    e.preventDefault();
    if ($(this).find('input[name="datenschutz"]')[0].checked === false)
      return false;
    // rest of form
Run Code Online (Sandbox Code Playgroud)

如果要添加消息,可以这样继续:

$(form).submit(function(e) {
    e.preventDefault();
    if ($(this).find('input[name="datenschutz"]')[0].checked === false) {
      alert("Please accept the terms and conditions!");
      return false;
    }
    // rest of form
Run Code Online (Sandbox Code Playgroud)