I'm currently learning JavaScript and trying to validate a simple form.
I'm using the revealing module pattern and using a for loop to check if input fields are empty on form submit.
The problem is that the validate function isn't firing and I see no errors in the console.
Also, If my JS can be improved please do let me know.
JSFiddle
HTML
<form action="" method="post" name="frm" id="form">
<input id="fullname" placeholder="Name" name="input">
<input id="email" placeholder="Email" name="input">
<input type="submit" id="submit">
</form>
JS
"use strict";
var signUp = (function() {
var formSubmit = function() {
var inputField = document.getElementsByTagName('input');
document.forms['frm'].onsubmit = function(e) {
alert('ello');
val();
e.preventDefault();
}
};
function val() {
var check = document.getElementsByName('input');
var len = check.length;
for(var i = 0; i < len; i++) {
if(check[i].length === "") {
alert('empty');
}
}
};
return {
init: formSubmit
}
})();
signUp.init();
2 Answers 2
val is firing, which you can see if you put an alert in at the beginning.
Instead of
check[i].length
you should have
check[i].value
4 Comments
value is specifically for reading the value of a field, innerHTML is a general way to access the contents of an element. An input field with a value filled in still won’t have anything in innerHTML.Actually your val() function is being called, your problem is with
EDIT: .length should .innerHTML.length < 1
See: http://jsfiddle.net/n4TvL/4/
if(check[i].innerHTML.length < 1) {
alert('empty');
}
2 Comments
innerHTML of a filled-in input field will still be of length 0. Your fiddle still gives the empty alert when the fields are filled in.
val()function actually is running. If you insert analert(len)aftervar len = check.length;it will alert 2. The problem is withif(check[i].length === "") {alert('empty');}... your condition is to check if check[i].length is an empty string. and thenalert('empty'), but since this never happens, the alert never happens. You want to docheck[i].valuenotcheck[i].length