Question

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.

Was it helpful?

Solution

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);
  });
});

OTHER TIPS

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
    }
  };
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top