Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 560
Keith Avatar asked Feb 21 '26 15:02

Keith


1 Answers

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");
   });
like image 136
epascarello Avatar answered Feb 23 '26 03:02

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!