hbbz040 hbbz040 - 7 months ago 18
Javascript Question

How to Populate Input Text Field with Javascript

I tried to collect data from JSON to fill out related Input Text Field after matching results, but it's not working.

How can I get populate the input text field from the JSON?

JS Code



$(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>




Answer

Two mistakes in your code.

First: Input does't have innerHTML but value. Second You are assigning integer to zipcode starting with zero. Rather you need a string type because value returned by input will be a string.

use this code

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>

Comments