2

I have one function, but two events. First event for input and keypress, second event for button and click.

  <input class="text">
  <button class="btn">Next</button>

And jquery code:

        function submit() {
          var inputValue = $( '.text' ).val();
          alert('inputValue');
        };

        $('.btn').on('click', function () {
          submit();
        });
        $('input').keydown(function(e) {
          if(e.which == 13) {
            submit();
          }
        });

Can I join these two events?

  • Possible duplicate of [jQuery multiple events to trigger the same function](http://stackoverflow.com/questions/2534089/jquery-multiple-events-to-trigger-the-same-function) – Nenroz Jan 26 '17 at 09:25
  • It looks like you're trying to emulate a `form`'s `submit` event listener. – pawel Jan 26 '17 at 09:26
  • 1
    https://jsfiddle.net/L2vrf8gd/ – pawel Jan 26 '17 at 09:31

3 Answers3

1

Try like this...

    $( '.btn, input' ).on( 'click keydown',  function ( event ) {
        if( ( event.type == 'click' )
            || ( event.type == 'keydown' && event.which  == 13 ) ) {
           //submit(); submit your form
           alert('hi');
        };
    } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="text">
<button class="btn">Next</button>
Hikmat Sijapati
  • 6,557
  • 1
  • 7
  • 18
0

Yes you can.

Add the same event listener for both the input and the button.

Then, inside the event handler check the type of the event. If the type is keyup, check for the correct key. If both satisfies (keyup and which === 13) you can submit. Otherwise, if the type is click, you can also submit.

Example: https://jsfiddle.net/p33kmbja/1/

Pimmol
  • 1,755
  • 1
  • 6
  • 13
0

e.type - we can determine type event - click or keydown.

$(e.target) - we get jQuery object, which was caused by an event.

e.which != 13 - determine push Enter.

$('.btn, input').on('click keydown', function (e) {
    if( (e.type == 'keydown')
         && $(e.target).is('input') 
         && (e.which != 13) ) return; 

    submit();
});
Alexandr Malyita
  • 526
  • 3
  • 15