ngplayground
ngplayground

Reputation: 21627

Checking Input Fields arent empty and firing the form

jQuery

$('.sendButton').click(function(e){
        e.preventDefault();
        var errors = 0;
        $("#steps input").each(function(){
            if ($.trim($(this).val()).length == 0){
                errors = 1;
            } else {
                errors = 2;
            }
        });
        if (errors == 2){
            $('#general').submit();
        }
    });

The above code works but it fires my form depending on how much inputs are within the #steps div. Could someone help me out only firing it once and only once?

The inputs inside #steps can vary between 1 input field and 4 depending on the amount the user has selected from a dropdown.

so the above code essentially checks that the amount fields chosen from the dropdown aren't empty when the user tries to submit the form.

So if I choose 2 from the dropdown, 2 inputs appear, and the form fires 2 times when the form values are filled up.

Upvotes: 0

Views: 86

Answers (1)

Adil
Adil

Reputation: 148120

Assuming you do not want to submit form if any of input is empty.

$('.sendButton').click(function(e){
    e.preventDefault();
    var errors = 0;
    $("#steps input").each(function(){
        if ($.trim($(this).val()).length == 0)
            errors = 1;           
    });
    if (errors != 1){
        $('#general').submit();
    }
});

Upvotes: 1

Related Questions