Reputation: 8582
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
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
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
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
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