简体   繁体   中英

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. 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:

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

( dataFieldMapping is the id of form). 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

$('#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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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