0

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;
    }
});
  • Also, the submit button's click handler is the wrong place to be validating forms. If the form is submitted by a means other than licking the button, such as pressing Enter, the validation function might not be called. Always use form.onsubmit for validation, not submitinput.onclick. – bobince Sep 09 '09 at 01:34
  • This makes sense, but does it work on an anchor tag click as well? I unerstand this solving the problem for pressing Enter at the end or mid form. –  Sep 09 '09 at 12:29

3 Answers3

7

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

You need

msg = msg.replace( blah )
Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
5

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).

Community
  • 1
  • 1
Adam Batkin
  • 51,711
  • 9
  • 123
  • 115
4

Try changing

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

to

msg = msg.replace(/Please enter your First Name\n/g, "");
jrummell
  • 42,637
  • 17
  • 112
  • 171