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

Answers 1

  • 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');
    }
    

Related Articles