0

I have a form with multiple added dynamic rows, and i want to do a little validation of the input before i submit the form, e.g. check if all fields have input and such. So i call this little function when i have an onclick-Event on my Submit-Button:

function validateAndSubmit() {
var form = document.getElementById("mainForm");
var formGroups = document.getElementsByClassName("form-group");
for (var x in formGroups) {
    // Validation goes here
    ....
    if (valid == false) {
        return;
    }
}
form.submit();

So in my logic, the code should iterate over each form-group (which basically represent the individual rows in the form) and check if they are valid. After the first invalid row, the function will return without any result. But if all formGroups are checked, the for-Loop will exit and the form.submit(); call will submit the form.

However, the final submit does not happen. Even if all form elements have valid input, the form does not submit. However, during some debugging i commented out the whole for-loop, and the form submits, but with no validation, of course. So i am assuming that somehow the for-loop does not exit properly, and could need some help with that problem.

The whole project is written in plain Javascript, however, the library i am using to dynamically add and remove items to the form bases on jQuery.

For reference, you can find the project online here

2 Answers 2

2

you shouldn't use for-in at the first place. Just use the plain for form:

for(var i=0;i<formGroups.length;i++)

remember, for-in is for Objects / dictionaries. eg. {'key':'value'}

the first "x" you got in your loop is "length" - your formGroups[x] became formGroups[undefined] and throw an exception instantly.

Sign up to request clarification or add additional context in comments.

3 Comments

Though your answer is correct, it's a funny thing, that formGroups in OP's code is actually an object, not an array. Can you explain the difference?
thanks, you pointed out an interesting fact: Array is a type of object in javascript, and .length() is a method of Array objects. The correct words should be "for-in is only for dictionaries..."
Actually I was after HTMLCollection, which is an object, not an array.
0

You could also use a jQuery selector to get the elements. In your example,

$('.form-control').each(function() {
    // Validation goes here
    console.log($(this));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.