javascript - 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 keyword1
and keyword2
values in my console?
解决方案
您错过#
了选择器。虽然我建议您使用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">
推荐阅读
- r - 你能在 R 中的 geom_point 图上组合一个 geom_bar 饼图吗?
- php - Wordpress - 原始 html 菜单上的活动类
- json - 解码没有属性名称的 JSON 数组
- django - RunPython.noop() 有什么作用?
- python-3.x - 熊猫在 groupby 对象上滚动斜坡
- wix - WIX 安装程序从 XmlConfig 元素中删除条目
- python - 如何使用python3计算计算器问题的负数?
- ios - 快速解码json数据
- reactjs - Aria-hidden 不会隐藏查询中的元素
- azure - 比较 Azure 数据工厂表达式中的日期