Abhi
Abhi

Reputation: 4271

Detect which event Submits the form

I have a form that I Submit by jQuery as well as when user clicks the Submit button:

Eg:-

jQuery submit

on some event

jQuery("#live_form").submit();

Button click submit

on button click

jQuery("#button1").click(function(){
  jQuery("#live_form").submit();
});

I need to execute a function(say func1) when the form is submitted by jQuery way and otherwise another function (say func2) when form submits on button click.

jQuery("#live_form").submit(function(){
  //some code
});

How can I distinguish between these submits without using global variables?

Upvotes: 2

Views: 107

Answers (3)

Anand Singh
Anand Singh

Reputation: 2363

You can use event.target.nodeName property to identify from which its submitted. Code here:

$("#yourform").submit(function(event){
if(event.target.nodeName=="BUTTON"){
 functionOne();
}else if(event.target.nodeName=="FORM"){
 functionTwo();
}
});

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

try:

       var fromWhere = {};
        jQuery("#button1").click(function(){
          fromWhere = $(this);
          jQuery("#live_form").submit();
        });

        jQuery("#live_form").submit(function(){
         fromWhere = $(this);
        });
        console.log(fromWhere);

Upvotes: 1

coolguy
coolguy

Reputation: 7954

jQuery("#button1").click(function(event){
  console.log("Form submit from "+event.target.nodeName);
  jQuery("#live_form").submit();
});

jQuery("#live_form").submit(function(event){
 console.log("Form submit from "+event.target.nodeName);
});

the first block returns BUTTON and second block return FORM

Upvotes: 3

Related Questions