0

I have an input that I want to allow the user to save the text either by pressing enter or by clicking anywhere else on the screen. Getting the code to process when the user presses enter is no problem. But I want to process the same code by triggering the jquery keyup event when the user clicks away just as if they pressed Enter on the input box instead. The theory isn't giving me an issue, but the keycode is either not being passed correctly or interpreted correctly when clicking away. When I alert the interpreted keycode, I get a "1" which doesn't equate to any keypress. What am I doing wrong?

$(document).on("click","body",function(e){      
 if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
  if($(".attributeEdit")[0]){ //This is a unique class added 
    var i = $.Event('keyup');
    i.which = 13; 
    $(".attributeEdit").trigger(i); //Have also tried triggering off #openInput, too with no success
  }
 }
});

$(document).on("keyup",".attributeEdit",function(){ 
 var keycode = (event.keyCode ? event.keyCode : event.which);
 if(keycode == '13'){
  do stuff; 
 }
 else{
  alert("keycode: " + keycode);  //This results in a "1" every time user clicks away
 }
});
redstang423
  • 123
  • 1
  • 1
  • 10
  • Mouse left click keycode is 1 – Atk Mar 17 '20 at 04:38
  • 1
    You can handle it by a function call, if you can not trigger specific event then just create UDF and call it on Keyup event and click on the body of HTML. – Hiren Raiyani Mar 17 '20 at 05:55
  • Many other solutions here: https://stackoverflow.com/questions/3368578/trigger-a-keypress-keydown-keyup-event-in-js-jquery – Hiren Raiyani Mar 17 '20 at 05:57
  • you need to learn about jquery focus out event – Harsimranjit Singh Mar 17 '20 at 09:53
  • @HirenRaiyani, I've tried to implement the solution(s) in the link you provided (you'll notice my first section of code is lifted directly from the accepted solution) but any solution I try still results in the keycode 1 interpretation from the next code block. – redstang423 Mar 18 '20 at 18:40

1 Answers1

0

I found a solution to the end objective using Hiren Raiyani's suggestion of a function call. It doesn't actually answer the original question, but since it solved my problem, I'm hoping this will be useful to others that search. I created a function to "do stuff" and that way, I can call that function both after the Enter key is pressed and after the mouse is clicked.

function doStuff(x,y){
  do stuff
}

$(document).on("click","body",function(e){      
  if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
    if($(".attributeEdit")[0]){ //This is a unique class added 
      doStuff(x,y);
    }
  }
});

$(document).on("keyup",".attributeEdit",function(){ 
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if(keycode == '13'){
    doStuff(x,y); 
  }
});
redstang423
  • 123
  • 1
  • 1
  • 10