-2

I have a text input where if the entry is alpha, an ajax routine ensues. If the text entry is numeric I want to avoid the ajax routine and run a different (non-ajax) routine, but ONLY if the Enter key is used. I'm having a rough time trying to figure out if there's an Enter at the end of the input string.

The following doesn't work:

thisVal=$(this).val();      // the user input value
endChar = thisVal.charCodeAt( thisVal.substr(thisVal.length) ) 

if (!isNaN(thisVal) && endhCar == 13){
    //Do the non-ajax routine
}

I've also tried thisVal.substr(-1). Same result. How do I code to get the enter key used or not? Help will be appreciated.

  • 3
    unless this is a textarea, pressing enter doesn't insert a character into the text input. – Kevin B Jul 14 '16 at 19:25
  • You need to capture keypress events and watch for 'enter' key that way. See for example: http://stackoverflow.com/questions/979662/how-to-detect-pressing-enter-on-keyboard-using-jquery – Nicholas Hirras Jul 14 '16 at 19:25
  • Yes, key stroke events are what you are looking for. newline is only added in elements that support multi-line input. See my answer. – Iceman Jul 14 '16 at 19:35

1 Answers1

1

Use key stroke events to identify <enter> because <enter> doesn't affect value of an input field. That happens only for text-areas. However, this technique works for any editable element.

$("#target").keyup(function(e) {
  var code = e.which;
  if (code == 13) {
    e.preventDefault();
    var data = ($(this).val());
    if (!isNaN(data)) {
      alert("DO numeric AJAX");
    } else {
      alert("DO alphanumeric AJAX");
    }
  }
});
<!DOCTYPE html>
<html>

<head>
  <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  TYPE AND HIT ENTER:
  <input id="target" type="text" />
  <br>DIFFERENT RESPONSE FOR NUMERIC & ALPHA NUMERIC INPUTS
</body>

</html>
Iceman
  • 6,035
  • 2
  • 23
  • 34
  • Thank you. I'll probably use your technique in the future. Meanwhile, I did a work-around by doing (return false) for numeric entries before they reach the ajax routine. If the user does a submit by pressing Enter, I put in an on('submit' routine for numeric entries. I hope this is clear. – Mffffffffffffff Jul 14 '16 at 23:55