String replacement in javascript

Asked

Viewed 163 times

-3

I have an input that receives a code composed of 4 letters

    <p>Localidade 
            <input type="text" id="localidade" oninput="MyFunction()">
            <span id="ca"></span>
    </p>

I intend to develop a function that receives this input and says the name of the aerodrome, as json file available at: https://pastebin.com/Y7gLPxR8

    function MyFunction() {
    var x = document.getElementById("localidade").value;
    var y = String(x);
    z = y.length;
    if (z === 4) {
    document.getElementById("ca").innerHTML = "Aeródromo: " + x;
    }
    else {
    document.getElementById("ca").innerHTML = "Aeródromo Inexistente:" + x;
    }
    }

What method can I use to extract data from this file and enter the aerodrome name in the above span? I thought about storing the data in a variable as vector, but it would get huge...

  • 1

    I was finishing the answer and you erased the question!!!! I’ll have to do it again!!!!

  • Excuse me, I wanted to edit and clicked on remove

  • 1

    I’m putting the answer. Don’t erase, and I won’t do it again.

2 answers

3


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;
      }
   }
});
  • 1

    Thank you, it worked perfectly. The previous author’s solution, although it could be adapted, still required the upload of the file, which I did not want. I will have to study more on AJAX from now on, as there will be several other similar cases.

2

To meet your requirements I made a modification in html. I put a <input file> to upload the file containing the aerodrome information so that it can be loaded from an arbitrary location. In my tests I used the path https://pastebin.com/raw/Y7gLPxR8 which is text-only version of content in Pastebin. Also a find button.

In Javascript and added the function openFile() which will be called as soon as a file is selected in<input file>. This function reads the selected file and converts JSON to object by placing the result in the variable aerodromos;

I changed the function MyFunction(), placing a query variable that holds the value that will be compared to the key CÓDIGO OACI.

I used the method find() qe returns the value of the first element of array which satisfies the test function provided. Otherwise, undefined is returned.

will be called at the event click of the locate button.

var aerodromos;

function openFile(event) {
  var input = event.target;
  var reader = new FileReader();
  reader.onload = function() {
    aerodromos = JSON.parse(reader.result);
  };
  reader.readAsText(input.files[0]);
};



function MyFunction() {
  var consulta = document.getElementById("localidade").value;

  var encontrado = aerodromos.find((elemento) => {
    if (elemento["CÓDIGO OACI"] == consulta) return elemento;
  });

  if (encontrado) console.log(encontrado);
  else console.log(consulta + "não encontrado");


}
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<div id='output'>

  <p>Localidade
    <input type="text" id="localidade">
    <button onclick="MyFunction()">Localizar</button>
    <span id="ca"></span>
  </p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.