I am new to JavaScript and am currently learning. I want to validate data on a form. But I want all errors to show up on one alert prompt box. For example, if a user does not type in their name and city, I do not want two alerts telling them to fill in the name field and then another after that saying that they need to fill in the city as well. I want to combine these into one, to create one alert that displays all validation errors. How would I do this? Here is some code I started with:
Code:<script language="javascript" type="text/javascript"> function checkName() { var myForm = document.pizzaForm; if (myForm.firstName.value == "" || myForm.lastName.value == "") { alert("Please type in your name"); return false; } else if (myForm.address.value == "") { alert("Please type in your address"); return false; } else { alert("Please type in your city"); return false; } } </script>
Thanks
One really great way to debug javascript is using Firefox's extension "Firebug." If you want to try it out do this:
Make sure you have Firefox with Firebug installed. In your code, if there is something you want to check you can write console.log( "message" ) or console.log( variable ). You can use this to give yourself messages or check variables. This is a great way to be able to search your available DOM objects or get a better handle on scope. It's also not as pesky as alert boxes. Let me know if you like it.
If you do want to use the alert box then you can just string concatenate your variables and strings using "+".
-CDG10620
Software Developer
You can't use an if-elseif-elseif-else structure for what you want. You need to concatenate the error message into a single string, with a separate if statement for each error message.
I would also suggest using a method name that better fits its purpose. checkName() implies that you are only checking the name. checkValues() or validateForm() seems like a better fit.
-CDG10620
Software Developer
Wrong subforum, someone should move the thread to Javascript.
thanks everyone
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks