Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind two events on two elements to one function in jquery?

Tags:

jquery

For example, I have a input text and a button

I want two events, button.on click and input.on KeyEnterPress to bind to one same function

How can I do that?

$('#search.onClick OR $searchText.onKeyEnterPress')
like image 204
Sato Avatar asked Mar 30 '16 02:03

Sato


People also ask

What is the difference between bind () and live () method in jQuery?

In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future.

How do I pass multiple events in JavaScript?

mouseMoveHandler, false); JQuery's bind allows multiple events, like so: $(window). bind('mousemove touchmove', function(e) { //do something; });

What is the purpose of using bind () method in jQuery?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.


1 Answers

Create a function to call:

function myfunc(event){
   // some code
}

You can do

$('#search').add($searchText).on('click keyup', myfunc);

OR if you ONLY want those on one (not both) do:

$('#search').on('click', myfunc);
$($searchText).on('keyup', myfunc);

NOTE Not clear if that last is a jQuery object but if so:

$searchText.on('keyup', myfunc);
like image 160
Mark Schultheiss Avatar answered Oct 14 '22 06:10

Mark Schultheiss