views:

856

answers:

4

A couple of questions here:

  • I was wondering what event do I use to execute some javascript on form submission (to do some validation)?
  • Once I have done my validation, how do I then submit the form in javascript ?

Cheers...

+5  A: 

Let's say you have a form named myForm:

var form = document.getElementById('myForm');

To catch submission:

try {
  form.addEventListener("submit", someFunction);
} catch(e) {
  form.attachEvent("submit", someFunction); //Internet Explorer
}

Note: If you want to stop the form from submitting, you make someFunction return false.

To submit the form:

form.submit();
musicfreak
+3  A: 

If you use jquery, it has a nice built-in form submission event hook that can make life very easy. Check out the following:

http://docs.jquery.com/Events/submit

jrista
+2  A: 

1) Are you looking for OnSubmit event?

2) You can call a function like validate() on onsubmit event and return false if validation fails. If false returned return false from the onsubmit function.

may be like,

<form name="test" OnSubmit = "return Submit()">

function Submit()
{
return Validate()
}

function Validate()
{
//Validation code goes here
}
blntechie
+4  A: 

You can use addEventListener(event, callback) but it's never been properly supported by Internet Explorer.

IE uses attachEvent(event, callback) instead.

I strongly recommend using a prebuilt addEvent function (lots available out there) or a library like jQuery, Prototype, Mootools, etc. since they all have excellent event handling functions built-in.

Gabriel Hurley