How to check the empty values of a dynamic form?

Asked

Viewed 931 times

3

How to use Jquery to attack the attribute name of all inputs and check if there is value

Current Code

Form:

...
<input type="text" name="nome[]" value="">
<input type="text" name="nome[]" value="">
<input type="text" name="nome[]" value="">
...

Javascript:

...
$('.cadastrar').on("click", function() {
    var nomes = $('input[name="nome[]"]');
    console.log(nomes);
});
...

I would have to check the value of each input and if there are any blanks it would return false and an Alert..

only I stopped when it was time to check field by field. I couldn’t continue.

3 answers

3


When you use jQuery like that: $('input[name="nome[]"]'); it will return an array with all inputs that have that name.

If you need to know which and/or how many are empty you can use the filter() and uses as return a condition that validates/invalidates the value of the input.

Within that .filter() it will iterate all inputs and if the return is valid it keeps this element in the array, so remove it.

To know how many and which empty inputs:

var vazios = $('input[name="nome[]"]').filter(function () {
    return this.value.split(' ').join('') == '';
});

then you can use the vazios.length to know how many.

Example: http://jsfiddle.net/nzgwgew4/

2

Use the function each

$('input[name="nome[]"]').each(function(i, item){
    if(item == "")
        console.log("vazio");
});

1

I believe this can help you.

$(' input[type=text]' ).each(
                function(index, element){
                    if(  $(element).val( ).length == 0 ){
                        $(element).focus( )
                        return false;
                    }
                }
            )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.