Foot Blogger Foot Blogger - 7 months ago 19
Javascript Question

Javascript Subscribe Form Validation Errors

I'm building a basic subscribe form which uses Javascript for validation, but it's not working correctly.

My Form code is:

<form id="pageSubscribeForm">
<div class="pageSubscribeCell">
<input id="pageSubscribeName" type="text" class="pageSubscribeInput" value="Tell Us Your Name" />
</div>
<div class="pageSubscribeCell">
<input id="pageSubscribeEmail" type="text" class="pageSubscribeInput" value="Add Your Email Address" />
</div>
<div class="pageSubscribeCell hidden">
<input id="pageSubscribeSpam" type="text" class="pageSubscribeInput" value="" />
</div>
<div class="pageSubscribeCell">
<div class="pageSubscribeButton">
<div id="pageSubscribeSubmit" class="pageSubscribeAction"></div>
</div>
</div>
</form>


And the validation code is:

$("#pageSubscribeSubmit").click(function() {
var name = $("#pageSubscribeName").val();
var nameok = 0;
var email = $("#pageSubscribeEmail").val();
var emailok = 0;
var spam = $("#pageSubscribeSpam").val();
var spamok = 0;
var dataString = 'name='+ name + '&email=' + email + '&spam=' + spam;

if(name!='Tell Us Your Name'){
nameok = 1
}else{
$("#pageSubscribeName").removeClass("subscribeSuccess").addClass("subscribeError");
}

if(email!='Add Your Your Email Address'){
emailok = 1
}else{
$("#pageSubscribeEmail").removeClass("subscribeSuccess").addClass("subscribeError");
}

if(spam ==''){
spamok = 1
}else{
$("#pageSubscribeSpam").removeClass("subscribeSuccess").addClass("subscribeError");
}

if(nameok == 1 && emailok == 1 && spamok == 1){
$('#pageSubscribeSubmit').hide();
}


When I click on the
submit
link I get the error class added to my Name cell but the email cell stays the same and the spam cell stays hidden. Any ideas why or how to fix?

Answer

Your email field doesn't get the error class because your test is checking the wrong text (2x 'Your'):

if(email!='Add Your Your Email Address'){

You also asked why "... the spam cell stays hidden ...". There is nothing in the code you posted which would remove the .hidden class from the div around #pageSubscribeSpam. Assuming your .hidden class does what it suggests, then the #pageSubscribeSpam input is hidden on page load. There is no way for a user to enter a value, so when the button is clicked, its value is still ''. So spamok = 1, always - it will never get the .subscribeError class added.