我想在数组中搜索一个值。 数组是用一些值预定义的。 将出现一个 HTML 文本框来输入值。用户需要输入该值。 如果用户输入的值在数组中。它应该显示“找到有值(value)的”,否则找不到。应该使用AJAX。 我的下面的代码不起作用。
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<p>Enter a value: <input type="text" id="carInput" onchange="textChanged()"></p>
<p id="onListText"></p>
<script>
var cars = ["abc", "def", "ghi","jkl"];
var textChanged = function(){
var inputText = $("#carInput").text();
if($.inArray(inputText, cars) !== -1){
$("#onListText").text("Value Found");
return;
}
}
</script>
</body>
</html>
最佳答案
var inputText = $("#carInput").text();
这应该是
var inputText = $("#carInput").val();
所以你的完整代码将是:
var cars = ["abc", "def", "ghi","jkl"];
var textChanged = function(){
var inputText = $("#carInput").val();
console.log(inputText);
if($.inArray(inputText, cars) !== -1){
$("#onListText").text("Value Found");
return;
} else {
$("#onListText").text("Value not Found");
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<p>Enter a value: <input type="text" id="carInput" oninput="textChanged()"></p>
<p id="onListText"></p>
关于javascript - 使用 javascript 通过用户输入搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29553746/