user3498478
user3498478

Reputation: 71

Jquery: how to trigger click event on pressing enter key or clicking button

I have a button that triggers a jquery event but only if the button is clicked. Is it possible to make it work if it is clicked or the return key is used?

$(document).ready(function () {
    var zipCodes = [60538, 60504];
    $("#buttontest").click(function () {
        var zipIndex = zipCodes.indexOf(parseInt($("#full_day").val()));
        $("#zipMessage > div").hide("fast");
        var zipId = zipIndex > -1 ? zipCodes[zipIndex] : "Error";
        $("#zip" + zipId).show("fast");
    });
});

Here is a working example; http://jsfiddle.net/7SPGh

Upvotes: 1

Views: 15817

Answers (8)

canon
canon

Reputation: 41675

As long as the button has focus, enter will trigger the click event. I think you mean you'd like to trigger a click if enter is pressed while the textbox has focus...

So, add a keydown handler to the textbox:

$(() => {
  $("#buttontest").click(e => console.log(`${e.target.id}:${e.type}`));
  $("#full_day").keydown(e => {
    if (e.which === 13) {
      $("#buttontest").triggerHandler("click");
      e.preventDefault();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id="full_day" />
<input type='button' id="buttontest" value="Enter Zip Code" />

Now, if you were using a form with a submit button, that'd be handled for you...

$(() => {
  $("form").on("submit", e => {
    console.log(`${e.target.id}:${e.type}`);
    e.preventDefault();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="zipForm">
  <input name="zip" value="90210">
  <button type="submit">submit</button>
</form>

Upvotes: 6

Scottyzen
Scottyzen

Reputation: 331

Try creating listeners for both key presses and mouse clicks:

function myFunction(e){
  if (e.which=='13' || e.type=='click'){
    // Run your code here
  }
}
$(document)
  .on('click', '#buttontest', myFunction)
  .on('keypress', this, myFunction);

Upvotes: 0

Jonathan Cohlmeyer
Jonathan Cohlmeyer

Reputation: 29

To improve upon canon's answer, you can bind to the key up or down event using jQuery's on event and look for the return key. Then you can check if an item that you want to trigger the click event on is in focus. Here I have used the hasClass to check if it is an appropriate item. Then you can trigger the click event on the item in focus.

$(window).on({
    keyup: function (event) {
        if (event.which === 13 && $(':focus').hasClass('item')) {
            $(':focus').trigger('click');
        }
    }
});

Upvotes: 0

Trim Kadriu
Trim Kadriu

Reputation: 451

Here is your working example:

http://jsfiddle.net/3JEKg/

Bind this in your element that you want to trigger the button click with Enter key Press

$('body').bind('keypress',function (event){
  if (event.keyCode === 13){
    $("#buttontest").trigger('click');
  }
});

Upvotes: 0

Laszlo Korte
Laszlo Korte

Reputation: 1179

You could wrap the input and the button into a form element an listen for the submit event:

<form id="form">
<input type='text' id="full_day"/>
<input type='submit' id="buttontest" value="Enter Zip Code"/>
</form>

$("#form").submit(function(e){
   e.preventDefault();
   // ...
});

http://jsfiddle.net/nJH3g/2/

Edit: type must be changed from button to submit to trigger the submit event.

Upvotes: 1

bitoiu
bitoiu

Reputation: 7474

Picking up your example, this is the solution: http://jsfiddle.net/7SPGh/7/

$(document).ready(function(){
  var zipCodes = [60538,60504];
  $("#buttontest").click(function(){
   var zipIndex = zipCodes.indexOf(parseInt($("#full_day").val()));
   $("#zipMessage > div").hide("fast");
   var zipId = zipIndex > -1 ? zipCodes[zipIndex] : "Error";
   $("#zip"+zipId).show("fast");

    });
    $("#full_day").keypress(function(e) {
        if(e.which == 13) {
        alert('You pressed enter!');
    }

  });
});

Upvotes: 0

lennon626
lennon626

Reputation: 124

Add another event listener for keypress. If the keycode is 13 (which is the return key), then run the function.

elem.addEventListener('keypress',function(){someFunc(e);}, false);

function someFunc(e){
if (e.keyCode === 13){

//run  your code

}

This is pure javascript.

Upvotes: 0

BFigueiredo
BFigueiredo

Reputation: 176

take a look at this discussion

$('#full_day').keypress(function(e) {
    if(e.which == 13) {
        jQuery(this).blur();
        jQuery('#buttontest').trigger("click");
    }
});

Upvotes: -1

Related Questions