开发者

get an instance of the form being submitted in javascript

开发者 https://www.devze.com 2023-01-05 22:26 出处:网络
I want to get a handle on the form being submitted, before submitting. There might be more than one form in the page

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 for开发者_运维百科m name/id

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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消