How to check the empty values of a dynamic form?

3

How to use Jquery to attack the name of all inputs and check for 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 is any blank it would return false and an alert ..

I just stopped to check field by field. I could not continue.

    
asked by anonymous 27.05.2015 / 15:45

3 answers

3

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

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

Within this .filter() it will iterate all the inputs and if the return is valid it keeps that element in the array, if it removes 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 vazios.length to know how many.

Example: link

    
27.05.2015 / 16:50
2

Use the each function

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

I think this might help you.

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