字符串末尾是<enter>吗?

时间:2016-07-14 19:23:15

标签: javascript jquery enter

我有一个文本输入,如果条目是alpha,则会发生ajax例程。如果文本条目是数字,我想避免使用ajax例程并运行不同的(非ajax)例程,但仅在使用Enter键时。我有一段艰难的时间试图弄清楚输入字符串末尾是否有输入。

以下不起作用:

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

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

我也试过这个Val.substr(-1)。结果相同。 如何使用或不使用输入密钥进行编码? 将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用关键笔划事件来标识<enter>,因为<enter>不会影响输入字段的值。这只发生在文本区域。但是,此技术适用于任何可编辑元素。

$("#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>

相关问题