Keith
Keith

Reputation: 4147

using keypress and click for submit

How do I make a click event and keypress work in the same if statement?

Right now I have :

if($('.test').is(':visible;)){
   $('button').click(function(e){
      ..do something here
    }else {
     ..do something here
 });

.test is the value field that when the user puts in the value I want them to be able to click the enter key, while they are in this box to submit the information or use the button to do so. This is not in a form, they are all in divs.

Upvotes: 3

Views: 1397

Answers (4)

epascarello
epascarello

Reputation: 207501

So put the logic into a common function and call it for click and keypress.

    (function () {
    
       function yourLogic () {
         $(".out").text($(".yourInput").val());
       }
    
       $("button").on("click", yourLogic);
       $(".yourInput").on("keyup", function (evt) {
           if (evt.which===13) yourLogic();
       });
    
    }());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="yourInput" />
<button>Click</button>
<div class="out"></div>

or do not use a common function and call the click() event on the button.

   $(".yourInput").on("keyup", function (evt) {
       if (evt.which===13) $("#yourButton").trigger("click");
   });

Upvotes: 6

sTx
sTx

Reputation: 1221

Or simply click on background

$(document).keypress(function(e) {
    if(e.which == 13) {
        $('button').trigger("click");
    }
});

//if($('.test').is(':visible;)){
   $('button').on("click",function(e){
      alert("click or enter");
       e.stopPropagation();
   });
//   }
 //  else {
  //   ..do something here
   //}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button>CLick me</button>

Upvotes: 0

Atif Tariq
Atif Tariq

Reputation: 2772

You can use it like this:

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

Upvotes: 0

Farside
Farside

Reputation: 10323

If you got a form, then bind submit handler:

$("form").submit(function(e){
    e.preventDefault();
    // your event handler here
}); 

It will be triggered when you press enter to submit the form, and when you click submit button at the same time.

Upvotes: 1

Related Questions