views:

34

answers:

3

I want to get a handle on the form being submitted, before submitting.

  1. There might be more than one form in the page
  2. I do not know the form name/id

reason: I want to do some tweeking before the form is being submitted in the template level.

A: 

With jQuery it'd be something like this:

$(function() {
  $('form').submit(function() {
    // the code goes here;
    // variable `this` is an instance of form
    alert($(this).className);
  });
});
Eimantas
A: 

If you use jQuery, you could look at doing something like this:

$("form").submit(function(e) {
    console.log("Form ID that is being submit %s",$(this).attr("id"));
});

In Pure javascript you could so something similar by doing a document.getElementsByTagName("form") and loop through the array you get.

SBUJOLD
+1  A: 

Without jQuery it'd be somthing like this:

for (var i=0; i < document.forms.length; i++){
  document.forms[i].onSubmit = function(){
    // logic goes here;
    // document.forms[i] is the instance of form
    if (formIsHappy()){
      return true; //form submits
    }else{
      return false; //prevents the submit
    }
  };
}
Jon Weers
+1 for "without jQuery"
Hippo
Heh, thanks! :)
Jon Weers