【问题标题】:Prevent form submit if checkbox is unchecked如果未选中复选框,则阻止表单提交
【发布时间】:2016-03-14 16:47:03
【问题描述】:

如果输入字段为空,我正在使用一些 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-Script 中实现的小脚本?

【问题讨论】:

  • varChecked = $('input[name="datenschutz"]:checked').length; if(Checked>0){ //在这里做事 }else{ //在这里做事 }

标签: javascript jquery ajax forms checkbox


【解决方案1】:

这样使用:

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

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

$(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

【讨论】:

  • 只是为了帮助改进一个微小的代码:$(form).find("input[name='datenschutz']"]) 所以它会找到该表单的复选框
  • 我“更正”了一个拼写实例,如果您不同意我的更改,我深表歉意。显然,如果您愿意,可以随意回滚。
  • @Cheshire 看看这个。我已将其包含在我的答案中。
  • @DavidThomas 这是完全正确的非正式方式。 :P如果你想让我专业一点,好吧,没问题。大声笑。
  • @PraveenKumar 不错 =)
【解决方案2】:

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

// 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});
});

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 1970-01-01
    • 2017-08-18
    • 2017-10-10
    • 2011-06-15
    • 2020-06-01
    • 2015-03-15
    • 2015-09-30
    • 2023-02-08
    相关资源
    最近更新 更多