You will have to use an AJAX to fetch the object inside the JSON where the key CÓDIGO OACI
is equal to the value entered in the input.
To do this, create a file with the extension .json
(example: dados.json
) and insert in it all the Pastebin code you reported.
Declare a variable with wider scope that will receive AJAX JSON (I used the variable var json;
). This variable will serve to store the return of AJAX only 1 time, that is, once this variable receives JSON, AJAX will no longer be triggered, avoiding multiple requests when changing the input value, because all JSON is already in memory in the variable json
.
Then you use a function (called busca()
) where you will check, using .filter()
, if there is an object in JSON with key CÓDIGO OACI
equal to the code that was typed and show the result in the span
.
Instead of using the attribute oninput
to call the function MyFunction()
, used a Event Listener, because thus you restrict the scope of objects within the function of the DOMContentLoaded
.
See how the code looks:
HTML:
<p>Localidade
<input type="text" id="localidade">
<span id="ca"></span>
</p>
JS:
document.addEventListener("DOMContentLoaded", function(){
var json;
document.getElementById("localidade").oninput = function(){
var x = this.value;
var z = x.length;
if(z == 4 && json){
busca(x);
}else if(z == 4){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
json = JSON.parse(this.responseText);
busca(x);
}
}
ajax.open("GET", "dados.json", true);
ajax.send();
}
}
function busca(cod){
var res = json.filter(function(obj){
return obj['CÓDIGO OACI'] == cod;
});
if(res.length){
document.getElementById("ca").innerHTML = "Aeródromo: " + res[0].NOME;
}else{
document.getElementById("ca").innerHTML = "Aeródromo Inexistente: " + cod;
}
}
});
I was finishing the answer and you erased the question!!!! I’ll have to do it again!!!!
– Augusto Vasques
Excuse me, I wanted to edit and clicked on remove
– Elender Góis Gallas
I’m putting the answer. Don’t erase, and I won’t do it again.
– Augusto Vasques