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

时间:2015-12-09 12:02:10

标签: javascript jquery ajax forms checkbox

如果输入字段为空,我使用一些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";
        });

  }

    });

});

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

<input type="checkbox" name="datenschutz" value="Datenschutz" required="required" >

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

2 个答案:

答案 0 :(得分:7)

使用这种方式:

/command "open ""sftp://uesrname:pwdhostname""" "get ""remoterservrpath"" localpath" "exit"

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

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

答案 1 :(得分:0)

我建议在选中复选框时启用提交按钮:

// binding an anonymous function to handle the change event:
$('input[name=datenschutz]').on('change', function () {
    var input = this;

    // navigating to the form 'this.form',
    // finding the submit button (obviously correct the
    // selector),
    // setting the disabled property of the submit button to
    // to be false when the check-box is checked, and true
    // when the check-box is unchecked:
    $(input.form).find('submitButtonSelector').prop('disabled', !input.checked});
});