首页 > 解决方案 > Javascript - Undefined Array of input field values on Enter click

问题描述

I have the following text input:

<input class="form-control" id="ar-array" type="text" name="ar-array" value="" placeholder="Type a keyword and hit return to add items to the array">

And my JavaScript code is the following:

var rowsArr = new Array();
  $("#ar-array").on('keyup', function (e) {
    if (e.keyCode == 13) {
      var item = $("ar-array").val();
      rowsArr.push(item);
      console.log(rowsArr);
    }
});

So, when I hit enter in my keyboard, my js code is supposed to add the value of my ar-array input field in the rowsArr, and it actually does that, but the value is undefined, here's my console log:

(2) [undefined, undefined]
0: undefined
1: undefined
length: 2

I get that result by typing something like keyword1 and hitting Enter, then I type keyword2 and hit Enter again. What am I doing wrong in my js code? Why can't I print the keyword1and keyword2 values in my console?

标签: javascriptphpjqueryarrays

解决方案


您错过#了选择器。虽然我建议您使用this来引用事件绑定到的当前元素:

var rowsArr = new Array();
$("#ar-array").on('keyup', function (e) {
  if (e.keyCode == 13) {
    var item = $(this).val();
    rowsArr.push(item);
    console.log(rowsArr);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control" id="ar-array" type="text" name="ar-array" value="" placeholder="Type a keyword and hit return to add items to the array">


推荐阅读