Search code examples
javascriptjqueryenter

Does the string have <Enter> at the end?


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.


Solution

  • 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>