I’m trying to make a JavaScript function that can validate a form. I keep thinking that the use of getElementByTagName(form) would work as a way to extract all inputs and in turn, cycle through them for proper validation sequences. Unfortunately, I’m lousy at JavaScript and for some reason, what I have so far isn’t even coming close to working.
Take the following as an example…
function validate(form){
var inputs = form.getElementByTagName('input');
if(!inputs){
alert('FALSE');
}else{
alert('TRUE');
}
}
I can’t seem to understand why “inputs” is undefined. I thought I was taking the form and throwing into the “validate” function where the “form.getElementByTagName” would have access to the subsequent elements indicated in the argument being passed (input) but apparently, I was way off.
Thanks for the great input and resources. I hope you can help me out with one more question…
Could someone explain to me what exactly form is within “function_name(form)”? Form is an argument, right? For some reason, I keep wanting to think that it behaves differently than your “normal” or traditional arguments due to the nature of which JavaScript plays with things…
Any clarification on this is appreciated. Oh, and I’m having some issues accessing some of the links you guys posted. I’m not sure if it’s me or the connection but I’ll try to look at those again later.
Yes, form is just an argument, and in the case of the validate function, the form argument would be a reference to the form element on the page.
That requires explicitly specifying the form from javascript.
Here’s an example:
var el = document.getElementById('someForm');
el.onsubmit = processSubmit();
function processSubmit() {
var form = this;
return validate(form);
}
The this keyword refers to the element that fired the onsubmit event.