user7244282
user7244282

Reputation:

How to combine the two events keypress and click

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?

Upvotes: 2

Views: 3065

Answers (3)

Oleksandr  Maliuta
Oleksandr Maliuta

Reputation: 516

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

Upvotes: 1

Pimmol
Pimmol

Reputation: 1871

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/

Upvotes: 0

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

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>

Upvotes: 2

Related Questions