jQuery的 - 如何取消表单提交防止条件为true时的默认值 [英] jQuery - How to cancel form submit prevent default when condition is true

查看:258
本文介绍了jQuery的 - 如何取消表单提交防止条件为true时的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个联系表单,当点击提交按钮时,我检查输入值,如果至少有一个输入为空,我运行一个alert并且preventDefault表单子表单,否则,我返回true。

I have a contact form that I check the input values when clicking on the submit button, if there's at least one input empty, I run an alert and preventDefault the form submition, else, I return true.

我的问题是,当我故意忽略一个输入时,我得到我想要的,但是如果我填充所有输入,我不能再提交表单...

My issue here is that when I deliberately omit an input, I get what I want, but then if I fill all the inputs, I can't submit the form any more...

 jQuery(document).ready(function () {
        jQuery('#envoyez').on('click', function () {
            jQuery(':input').each(function () {
                const val = jQuery.trim(jQuery(this).val());
                if (val.length == 0) {
        alert('Fill all the inputs please');
                     jQuery("form").submit(function(e){
                     e.preventDefault();
                         });
                } else {
                    return true;
                }
            })
        })
    })

谢谢

Thanks

推荐答案

您应该在 .ready()函数中声明表单事件侦听器。然后创建一个处理表单有效性的变量。

You should declare the form event listener in your .ready() function. Then create a variable that handles validity of the form.

jQuery(document).ready(function () {

    // count the number of inputs that are filled.
    var clearCount = 0;

    jQuery("form").submit(function(e) {

        // here check if clearcount is not equal to the number of fields
        if (clearCount != jQuery(':input').length)
        {
            // this means that one of the fields are not filled
            e.preventDefault();
            return false;
        }
    });

    jQuery('#envoyez').on('click', function () {

      // reset clearcount for revalidation
      clearCount = 0;

      jQuery(':input').each(function () {
          const val = jQuery.trim(jQuery(this).val());
          // check if input is not empty.
          if (val.length > 0) {
              clearCount++;
          }
      })
  })

});

这只是解决问题的简单方法,但如果您想要一种更好的方法,只需简单地:

This is just a simple approach of fixing your problem though if you want a way more better method you could just simply:

jQuery(document).ready(function () {

    jQuery("form").submit(function(e) {

        // check if one of the fields are empty
        // and so on
        if (   jQuery(this).find("input[name='NAME1']").val().length == 0
            || jQuery(this).find("input[name='NAME2]").val().length == 0
            || jQuery(this).find("input[name='NAME3']").val().length == 0)
        {
            // this means that one of the fields are not filled
            e.preventDefault();
            return false;
        }
    });
});

希望有所帮助

这篇关于jQuery的 - 如何取消表单提交防止条件为true时的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆