views:

43

answers:

1

Hello friends, I have this code in my view

function Validate() {
   if (document.getElementById('MandateName').value == "") {

       var err = document.getElementById('MandateNameErr');
       err.innerHTML = "Please enter a value for the Mandate Name";
       err.style.display = "block";
       return false;
   }
   else {
       document.getElementById('MandateNameErr').style.display = "none";
   }

   if (document.getElementById('MandateDescription').value == "") {
       var err = document.getElementById('MandateDescriptionErr');
       err.innerHTML = "Please enter a value for the Mandate Description";
       err.style.display = "block";
       return false;
   }
   else {
       document.getElementById('MandateDescriptionErr').style.display = "none";
   }

   return true;
}

and I have on submit button I am validating before submiting?

<button name="Submit" onclick="Validate()" >Add Variables to Mandate</button>

I called Validate funtion but its shwoing me if I am not entering anything on the text box if I click Button its showing me my validation message but same time its going to my view and throwing me the message?

even I put the return false; its not working is that something I am doing wrong? Thanks

+3  A: 

You need to put return in the onclick, like this:

<button name="Submit" onclick="return Validate()" >Add Variables to Mandate</button>

Otherwise you're executing the validation...but not really caring about the result.

Nick Craver
@Nick......forgetting the return, is the most common mistake in calling js functions
Yogendra
The most common mistake? How about a very common mistake in a deprecated style of attaching events? If you separate your script from the html, this won't happen.
Juan Mendes
@Juan - While I agree, I find fault with your argument, `$("button").click(function() { Validate(); });` would have the *exact* same issue, it would need to be `$("button").click(function() { return Validate(); });` or `$("button").click(Validate);`
Nick Craver
I see... I guess returning false to prevent the default action is what should be deprecated, in favor of preventDefault
Juan Mendes