Home > Software design >  send data from response to html
send data from response to html

Time:10-12

How to i send the data i got from a axios response to my html input textbox?

this is my axios code

let cp = document.querySelector('input[name=codigopostal]');
    let codigo = cp.value;

    cp.value='';

    axios.get(`https://api.duminio.com/ptcp/ptapi615ae094f3e579.37295368/${codigo}`)
        .then(function(response){
            if(response.data.Distrito !== null){
                console.log(response.data);
                txtDistrito = document.createTextNode(response.data.Distrito);
                txtConcelho = document.createTextNode(response.data.Concelho);
                txtFreguesia = document.createTextNode(response.data.Freguesia);```

I have 3 input textboxs:

input type="text" id="id="cidade" name="cidade"
input type="text" id="id="concelho" name="concelho"
input type="text" id="id="Distrito" name="Distrito"

And i want to send the data from txtDistrito to the input with id="Distrito"

CodePudding user response:

I guess you need to select element by ID if it's already in DOM

if(response.data.Distrito !== null){
  console.log(response.data);
  txtDistrito = document.getElementById("Distrito").value = response.data.Distrito;
  ...

If It's not in the DOM, you'd need to do something like:

var input = document.createElement("input");
input.type = "text";
input.name = "Distrito";
input.id = "Distrito"; 
input.value = response.data.Distrito;
container.appendChild(input); // put it into the DOM

  • Related