gpt4 book ai didi

javascript - 如何使用 Javascript 填充输入文本字段

转载 作者:太空狗 更新时间:2023-10-29 15:48:50 26 4
gpt4 key购买 nike

在匹配结果后,我尝试从 JSON 中收集数据以填写相关的输入文本字段,但它不起作用。

如何从 JSON 填充输入文本字段?

JS 代码

$(document).ready(function(){
var filter = document.getElementById('zipcode');
var JSONtbl = [
{"zipcode":01702,"address":"334 CONCORD ST","County":"MIDDLESEX"},
{"zipcode":02482,"address":"27 Atwood St","County":"NORFOLK"},
{"zipcode":02459,"address":"189 Cypress St","County":"MIDDLESEX"}
];
filter.onkeyup = function() {
var zipcodeToSearch = filter.value;
var n = zipcodeToSearch.length;
if (n < 5) {
document.getElementById("address").innerHTML = "";
document.getElementById("County").innerHTML = "";
} else {
for (var i = 0; i < JSONtbl.length; i++) {
if (JSONtbl[i].zipcode == zipcodeToSearch) {
document.getElementById("address").innerHTML = JSONtbl[i].address;
document.getElementById("County").innerHTML = JSONtbl[i].County;
}
}
if (document.getElementById("address").innerHTML == "") {
alert("ZipCode Out Of Area")
}
}
};
});
div {
padding: 2px 5px;
}
<form method="post">
<div><input type="text" id="zipcode"/></div>
<div><input type="text" id="address" disabled="disabled"></div>
<div><input type="text" id="County" disabled="disabled"></div>
</form>

最佳答案

您的代码中有两个错误。

第一: Input 没有 innerHTML 但有值。第二 您正在将整数分配给从零开始的邮政编码。相反,您需要一个字符串类型,因为输入返回的值将是一个字符串。

使用此代码

var filter = document.getElementById('zipcode');
var JSONtbl = [
{"zipcode":"01702","address":"334 CONCORD ST","County":"MIDDLESEX"},
{"zipcode":"02482","address":"27 Atwood St","County":"NORFOLK"},
{"zipcode":"02459","address":"189 Cypress St","County":"MIDDLESEX"}
];
filter.onkeyup = function() {
var zipcodeToSearch = filter.value;
var n = zipcodeToSearch.length;
if (n < 5) {
document.getElementById("address").value = "";
document.getElementById("County").value = "";
} else {
for (var i = 0; i < JSONtbl.length; i++) {

if (JSONtbl[i].zipcode == zipcodeToSearch) {

document.getElementById("address").value = JSONtbl[i].address;
document.getElementById("County").value = JSONtbl[i].County;
}
}
if (document.getElementById("address").value == "") {
alert("ZipCode Out Of Area")
}
}
};
div {
padding: 2px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post">
<div><input type="text" id="zipcode"/></div>
<div><input type="text" id="address" disabled="disabled"></div>
<div><input type="text" id="County" disabled="disabled"></div>
</form>

关于javascript - 如何使用 Javascript 填充输入文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36752258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com