Sato
Sato

Reputation: 8582

how to bind two events on two elements to one function in 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')

Upvotes: 7

Views: 2424

Answers (4)

Shashank
Shashank

Reputation: 2060

Refer demo.

Please find the code below:

HTML:

<div>
  <input type="text" id="searchText" placeholder="Type soemthing" />
  <br>
  <br>
  <button id="search">
    Click Me
  </button>
</div>

JS:

$(function() {
  $('#search').on('click', execute);
  $('#searchText').on('keyup', execute);
});

function execute() {
  alert('Event Fired');
}

Upvotes: 0

Mark Schultheiss
Mark Schultheiss

Reputation: 34158

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

Upvotes: 3

mmativ
mmativ

Reputation: 1414

this is the approach you want or not?

$('.but').on('click keyup',function(){
	if ( event.which == 13 ) {
     console.log('1');
     return;
  }
	console.log('1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="but">

Upvotes: 1

sdesapio
sdesapio

Reputation: 138

function doOneThing(){
    console.log('Do one thing.');
}

$("#search_input").on('keypress', function(e) {
    if (e.which === 13) {
         doOneThing();
    }
});

$("#search_button").on('click', function(e) {
     doOneThing();
});

Upvotes: 1

Related Questions