Vadzim Savenok Vadzim Savenok - 4 months ago 19
Javascript Question

Use a preventdefault to get out of the loop after pressing Enter key

This is a complete revision of my initial question, all unnecessary resources and references were deleted

I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:

var funcelement = function(){
//function code
};


$('#buttonID').click(funcelement);


$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})


What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().

So I tried various combinations to make it work. The following is the latest result on my attempts

$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;

if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}

else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}

}
})


After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.

However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.

How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.

Answer

You can pass a parameter to into the function and stop the propagation there like so:

var funcelement = function(event, wasTriggeredByEnterKey){
   if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
       event.stopPropagation;
   }

    //function code
};


$('#buttonID').click(funcelement);



$('#inputID').keyup(function () {
    if (event.which == 13) {
        $('#buttonID').trigger('click', [true]);
    }
  }
)

UPDATE

In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:

$('#inputID').keydown(function () {
   var hasfocus = $('#buttonID').is(':focus') || false;

   if (event.which == 13) {
      if (!hasfocus) {
         event.preventDefault();
         $('#buttonID').trigger('click');
         //hasfocus = true;
      }

      else {
         //event.preventDefault();
         //$('#buttonID').trigger('click');
     }

   }
})