[英]Search array elements using html form with javascript
我在下面的代码中尝试做的是创建一个搜索表单,当搜索输入与任何数组元素匹配时,都会弹出一个警报。到目前为止,它不起作用。 我认为问题是我不确定如何在if语句的第一行中写出逻辑。
<form>
<input type="text" id="formInput"></input>
<input type = "button" id="search"></input>
</form>
<script>
var search = document.getElementById("search");
var formInput = document.getElementById("formInput").value;
var data = ["yay"];
search.onclick = function(){
for (i=0; i<data.length; i++){
if (data[i] === formInput) {
alert(data[i]);
}
else{ alert("not working yet"); }
}
};
</script>
将获得输入的行移到onclick函数中:
<form>
<input type="text" id="formInput"></input>
<input type="button" id="search"></input>
</form>
<script>
var search = document.getElementById("search");
var data = ["yay"];
search.onclick = function() {
var formInput = document.getElementById("formInput").value;
for (i=0; i<data.length; i++){
if (data[i] == formInput) {
alert(data[i]);
} else {
alert("not working yet");
}
}
};
</script>
当前,页面加载时(在用户有机会输入任何内容之前),它仅读取一次表单输入。 如果将该行放在onclick
函数中,则它将在搜索数组之前检查输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.