user1170330 user1170330 - 4 months ago 13
Javascript Question

Combine several events

I have a text field and a button. Either when the button is clicked or enter is hit, a function should be executed.

My approach works is intended. However, is it possible to combine those 2 functions (

click
and
keypress
), so that I only have 1?

$("button").click(function() {
getInput();
});

$("#name").keypress(function(e) {
if (e.which == 13) {
getInput();
}
});

function getInput() {
alert($("#name").val())
}


So I need to just append those events.

Here is a fiddle.

Answer

You can listen for multiple events using .on('listOfEvents')

Than you just need some additional rules to check when you need to run function.

$("button, #name").on('click keypress', function(e) {
    if ($(e.currentTarget).attr('id') == 'submit' || e.which == 13) {
	  	getInput();
    }
});

function getInput() {
    alert($("#name").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" />
<button id="submit">
  OK
</button>