Two different elements to "send" and click events processed by the same jquery function?

I have a submit button #next_step and a link #design_next_step .

When a button is clicked or a link is clicked, the same function starts.

How can I do something like this?

$('#next_step').submit(), $('#design_next_step').click(){function(){ ... });

+4
source share
6 answers

Just run both event handlers to call the same function F.

 $('#next_step').submit(function() { F(); }); $('#design_next_step').click(function() { F(); }); var F=function() { . . .Write code here } 
+4
source

You can use the standard CSS comma to define a group selector:

 $('#next_step, #design_next_step').on('submit click', function(){ ... }); 

When you click a button or link to a link ...

But the buttons are not sent, they are pressed. The submit event is for form elements, not button or input elements. Assuming you have specified id for elements that are buttons or links, just use the click event:

 $('#next_step, #design_next_step').on('click', function(){ ... }); 

Depending on what you are doing, you may or may not want to prevent the default action for the event [by accepting the event argument and calling preventDefault on it or doing return false in a handler that will prevent the default propagation and stop propagating]. The default action for click in links is, for example, a link to a link.

+5
source

you can specify the same class for both the link and the button, and then you can try the following

 $('.className').click(function() { var item = $(this); // item that triggered the event }); 

and if you want to do based on identifiers, then follow

 $('#Button1, #Link1').click(function() { // You can use `this` to refer to the source element, for instance: }); 
+2
source

I think there is no such way

Instead, try using the same function in event handlers

 $('#formId').submit(function{ execute(); }); $('#design_next_step').click(function{ execute(); }) 
0
source

That would be more appropriate.

 $('.anchor').click(function{ $('form').submit(); }); 
0
source

Maybe you can just call it as if you were calling a normal function. Since in this case submit and click perform the same action when the user submits or clicks a link, they call funcion "myFunction"

  function myFunction() { .......... } $('#button').submit(myFunction); $('#link').click(myFunction); 

or

  var myFunction=function() { ....... } $('#button').submit(myFunction); $('#link').click(myFunction); 
0
source

Source: https://habr.com/ru/post/1487607/


All Articles