DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   JavaScript / DHTML / AJAX (http://www.daniweb.com/forums/forum117.html)
-   -   Alert box, then cancel action (Javascript) (http://www.daniweb.com/forums/thread61871.html)

ForestTech Nov 17th, 2006 1:51 am
Alert box, then cancel action (Javascript)
 
Hi,

I'm trying to write a form that has required fields. When the form is filled out with the required fields missing, I'm trying to have a pop-up that tells them what is missing and then cancels the submission of the form.

At the moment I have the function below linked into the the Submit button like so: <submit onClick="validateForm()">

[html]function validateForm(){
var form_object = document.forms.helpform;
if(form_object.elements.Name.value == ''){
alert('Please enter your name.');
return false;
} else if(form_object.elements.Email.value == ''){
alert('Please enter your email address');
return false;
} else if(form_object.elements.Mobile.value == ''){
alert('Please enter your mobile phone number');
return false;
} else if(form_object.elements.Description.value == ''){
alert('Please enter a description of what you would like us to help you with.');
return false;
}
return true;
}[/html]


I have the function in the the head of the document.

The pop-ups work fine, but it doesn't cancel the form from submitting. If anyone has any suggestions, they would be most appreciated

Thanks in Advance

vishesh Nov 17th, 2006 4:26 am
Re: Alert box, then cancel action (Javascript)
 
use this code
Quote:

<form onSubmit="return validateForm()">

ForestTech Nov 19th, 2006 7:27 pm
Re: Alert box, then cancel action (Javascript)
 
That didn't seem to work. The code works, except that it doesn't stop the form submission process. Does anyone know of any code that would stop the current action or anything like that. I know a little bit of javascript, but I'm still on the learning curve.

tgreer Nov 19th, 2006 9:16 pm
Re: Alert box, then cancel action (Javascript)
 
That should work. You need to return either true or false, and call the function using the "return" keyword as vishesh has shown. He's missing the terminal semicolon, but it should still work. Also, you can't code both an "onsubmit" for the form AND "onclick" on the submit button. Your code would run twice. Pick a single event handler, use the "return" keyword, and make sure each code path in your function returns either "true" or "false".

ForestTech Nov 20th, 2006 2:22 am
Re: Alert box, then cancel action (Javascript)
 
Problem solved. Thanks guys


All times are GMT -4. The time now is 7:57 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC