admin管理员组

文章数量:1291522

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;

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/7SPGh

Share Improve this question edited Apr 4, 2014 at 17:08 Greg 2,1731 gold badge22 silver badges23 bronze badges asked Apr 4, 2014 at 17:06 user3498478user3498478 711 gold badge1 silver badge8 bronze badges 2
  • As long as the button has focus, the enter key will trigger the click. I think you mean you'd like to trigger the click if enter is pressed while the textbox has focus... – canon Commented Apr 4, 2014 at 17:09
  • possible duplicate of Enter key press event in JavaScript – morten.c Commented Apr 4, 2014 at 17:10
Add a ment  | 

8 Answers 8

Reset to default 6

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./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./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="zipForm">
  <input name="zip" value="90210">
  <button type="submit">submit</button>
</form>

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/nJH3g/2/

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

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.

Picking up your example, this is the solution: http://jsfiddle/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!');
    }

  });
});

Here is your working example:

http://jsfiddle/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');
  }
});

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

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

take a look at this discussion

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

本文标签: javascriptJquery how to trigger click event on pressing enter key or clicking buttonStack Overflow