Combining two event handlers, jQuery

I have two events that I want to observe at the facility,

input.blur(function(event) {
  ajaxSubmit(this);
  event.preventDefault();
});

form.submit(function(event) {
  ajaxSubmit(this);
  event.preventDefault();
});

But I feel that it is not dry enough, can I connect two events with my object inputand fulfill my function ajaxSubmit()if there is fire?


Which would be great if you could:

input.bind("blur", "submit", function(event) {
  ajaxSubmit(this);
  event.preventDefault();
});
+3
source share
2 answers

You can use the on method

$("#yourinput").on("blur submit", functionname);

It can combine any number of events; Separate them with a space.

+10
source

Yes, just declare the function, and then bind it to events:

var ajaxCallback = function(event){
  ajaxSubmit(this);
  event.preventDefault();
};

input.blur(ajaxCallback);
form.submit(ajaxCallback);

Note on variable declaration:

@cletus, , , , , . , . , , , :

function ajaxCallback(event){ ... }

, , .blur .submit.

+4

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


All Articles