简体   繁体   English

检查表单中的所有输入文本字段是否为空提交,如果至少填写了一个文本字段则忽略

[英]Check All input text fields in form empty or not on Submission, Ignore if at least one text field is filled

Here is the situation 情况就是这样

I have a form with many input fields in my JSP page. 我的JSP页面中有一个包含许多输入字段的表单。 The number of input text fields are unknown as it is based on the previous action class. 输入文本字段的数量未知,因为它基于前一个操作类。

When the form is submitting, I want to check all input text fields are empty or not. 当表单提交时,我想检查所有输入文本字段是否为空。 If all are empty, then it should not submit. 如果全部为空,则不应提交。 Otherwise( in any case. ie, at least one text field must be filled), then form should submit. 否则(在任何情况下,即必须填写至少一个文本字段),然后表格应提交。

The JQuery I have tried: 我尝试过的JQuery:

$('#dataFieldMapping').submit(function() {
    if ($('input:text').is(":empty")) {
        alert("Empty!");
        preventDefault();
     }
});

( dataFieldMapping is the id of form). dataFieldMapping是表单的id)。 When I click on submit, it alerts with "Empty!" 当我点击提交时,它会提醒“空!” always, even if all text fields are filled. 总是,即使所有文本字段都填满了。

NB : My submit button is outside of form. 注意 :我的提交按钮不在表单范围内。 So I was using 所以我在用

$('#dataFieldMapping').submit();

without validating. 没有验证。 But I want to validate the form. 但我想验证表格。

DEMO DEMO

$('#dataFieldMapping').submit(function (e) {
    if (!$(this).find('input:text').filter(function () {
        return $.trim(this.value) != ""
    }).length) {
        alert("Empty!");
        e.preventDefault();
    }
});

You are not calling preventDefault on event object, you need to call preventDefault on event object. 您没有在事件对象上调用preventDefault,您需要在事件对象上调用preventDefault The way you are trying to check that all fields are empty wont give you correct result as it will checks children not value. 你试图检查所有字段是否为空的方式不会给你正确的结果,因为它会检查孩子没有价值。

:empty Select all elements that have no children (including text nodes), reference :empty选择所有没有子元素的元素(包括文本节点), 引用

$('#dataFieldMapping').submit(function(event) {
    lst = $('input:text').filter(function(){
         this.value != "";
     });
    if(lst.length)
    {
       alert("Empty!");
       preventDefault();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM