views:

205

answers:

3

I have no idea why this doesn't work, but doing some validation functions and trying to output a dynamic message to an alert when they hit submit and forgot to fill out a field. It works only on the second click of the submit button, as far as removing the string, everything else works when it should.

Here's the code:

var fname = $('#fname');
var lname = $('#lname');

function validatefname(){
var a = fname.val().length;

if(a < 2) {
 fname.prev().addClass("error");
 if(msg.search("First Name") == -1) {
   msg+= "-Please enter your First Name\n";
 }
 return false;
} else {
 fname.prev().removeClass("error");
 msg.replace(/Please enter your First Name\n/g, "");
 return true;
}
}

fname.blur(validatefname);
fname.keyup(validatefname);

step4submit.click(function(){
 if(validatefname()) {
  step4form.submit();
  return true
 } else {
  msg+= "\nPlease fill out the fields marked in red";
  alert(msg);
  msg = "";
  return false;
 }
});
+6  A: 

String.replace returns a new string, rather than editing the string that makes the replace call.

You need

msg = msg.replace( blah )
Stefan Kendall
+4  A: 

Try changing

msg.replace(/Please enter your First Name\n/g, "");

to

msg = msg.replace(/Please enter your First Name\n/g, "");
jrummell
+5  A: 

In JavaScript, Strings are immutable, they can never change. So if you are calling a function to modify a string in some way, that function will return a new string with your changes, rather than modify the original string.

Change the line that is performing the replacement to save the result of the replacement back into the original variable, like so:

msg = msg.replace(/Please enter your First Name\n/g, "");

(there are various performance and safety reasons for this, but that is for another day/another question).

Adam Batkin