In my HTML, I have a large form (id ="myform") that asks users to fill in 5 fields for Date of Birth (dobDOB), Sex, Weight, Hair Color and Eye Color and then several other fields which don't relate to this question. EachEach of those 5 category fields start with a question mark in it. When the users enters something, the question mark goes away. SoSo my JS (which you'll see in a few seconds) looks for a question mark. If it's there, user missed the field. IfIf it's not, the user entered something.
I am validating each field using the javascript belowthis JavaScript:
$('#myform').submit(function(){
//check to make sure all categories have been guessed
var $dobdisplaytext=$('#dob-display').text();
var $sexdisplaytext=$('#sex-display').text();
var $weightdisplaytext=$('#weight-display').text();
var $hairdisplaytext=$('#hair-display').text();
var $eyedisplaytext=$('#eye-display').text();
if ( $dobdisplaytext.indexOf('?') !== -1 ) {
$('#dob-display-error').show();
$('#dob').addClass('error-border');
$('html,body').animate({scrollTop:0},0);
return false;
}
if ( $sexdisplaytext.indexOf('?') !== -1 ) {
$('#sex-display-error').show();
$('#sex').addClass('error-border');
$('html,body').animate({scrollTop:0},0);
return false;
}
if ( $weightdisplaytext.indexOf('?') !== -1 ) {
$('#weight-display-error').show();
$('#weight').addClass('error-border');
$('html,body').animate({scrollTop:0},0);
return false;
}
if ( $hairdisplaytext.indexOf('?') !== -1 ) {
$('#hair-display-error').show();
$('#hair').addClass('error-border');
$('html,body').animate({scrollTop:0},0);
return false;
}
if ( $eyedisplaytext.indexOf('?') !== -1 ) {
$('#eye-display-error').show();
$('#eye').addClass('error-border');
$('html,body').animate({scrollTop:0},0);
return false;
}
});
Anyway, thisThis code above works. However, however, here are a few things I'd like help with...:
I am not even close to a JS expert as I'm sure you can all tell, but there has to be a more efficient way to write this, right? LikeLike in a loop of some sort? With the key being that if four fields are missed, I'd like all four fields to show their respective alerts.
I believe this will be answered by being written better and I alluded to it in #1 but just to be clear and give more details... If I remove
return false;
from each one, ALL missed categories show the required error/border at once (which I prefer) but of course the form then immediately submits because I have nothing stopping it.
So I know return false;
has got to go SOMEWHERE (and likely only once, once the code is written more efficiently), just not sure where.
Any help/suggestions would be appreciated.
Thanks!