Popular inputs with Json file in jQuery

Asked

Viewed 884 times

1

I would like to know how to fill in some inputs through data from a json file with jQuery.

Follow the data in Json:

{"data":[
{"id":"0","lNeg":"","cnpjToma":"02.558.157/1001-62","nDoc":"00121961","nPed":"5100484612","dtEmis":"01/11/2016","dtVenc":"01/01/2017","munic":"SÃO PAULO","codNat":"17.06","opts":"","tipoDoc":"","vIcms":"","vDoc":"","irrf":"","inss":"","iss":"","pis":"","cofins":"","cssl":"","Obs":""},
{"id":"1","lNeg":"","cnpjToma":"20.558.756/1232-01","nDoc":"23463546","nPed":"1234979878","dtEmis":"23/01/2016","dtVenc":"25/10/2017","munic":"CAMPINAS","codNat":"12.01","opts":"","tipoDoc":"","vIcms":"","vDoc":"","irrf":"","inss":"","iss":"","pis":"","cofins":"","cssl":"","Obs":""},
{"id":"2","lNeg":"","cnpjToma":"09.333.000/1000-89","nDoc":"98984776","nPed":"7896563535","dtEmis":"09/05/2016","dtVenc":"19/12/2017","munic":"INDAIATUBA","codNat":"14.56","opts":"","tipoDoc":"","vIcms":"","vDoc":"","irrf":"","inss":"","iss":"","pis":"","cofins":"","cssl":"","Obs":""},
{"id":"3","lNeg":"","cnpjToma":"43.115.201/1203-79","nDoc":"24984333","nPed":"4676563531","dtEmis":"08/03/2016","dtVenc":"10/05/2017","munic":"SALTO","codNat":"01.99","opts":"","tipoDoc":"","vIcms":"","vDoc":"","irrf":"","inss":"","iss":"","pis":"","cofins":"","cssl":"","Obs":""},
{"id":"4","lNeg":"","cnpjToma":"11.551.151/1011-62","nDoc":"10121962","nPed":"9900484743","dtEmis":"11/11/2016","dtVenc":"02/03/2017","munic":"ITU","codNat":"13.06","opts":"","tipoDoc":"","vIcms":"","vDoc":"","irrf":"","inss":"","iss":"","pis":"","cofins":"","cssl":"","Obs":""}          
]}

Follows the inputs in html:

<div class="col-md-2">
    <label for="cnpjToma">CNPJ tomador:</label>
    <input type="text" class="form-control" id="cnpjToma" name="cnpjToma">
</div>
<div class="col-md-2">
    <label for="nDoc">N° do docum:</label>
    <input type="text" class="form-control" id="nDoc">
</div>
<div class="col-md-2">
    <label for="nPed" class="text-danger">N° do pedido:</label>
    <input type="text" class="form-control" id="nPed">
</div>
<div class="col-md-2">
    <label for="dtEmis">Data de emissão:</label>
    <input type="text" class="form-control" id="dtEmis">
</div>
<div class="col-md-2">
    <label for="dtVenc">Data de vencim:</label>
    <input type="text" class="form-control" id="dtVenc">
</div>

Follow the jQuery:

$(document).ready(function(){

var dados;
    $.ajax({
        url: "detalhes.json",
        success: function(data){
            dados = data;
        }
    });

var populateInputs = function(data){
    for (var prop in data){
        var val = data[prop];
            $("#" + prop).val(val);
    };
};
    populateInputs(dados[0]);
  })
  • Where is this JSON file? You will need to make a request to the server to read it.

  • In the same root directory of the project, on my machine.

  • The data in data form an array. You need to indicate exactly how you want to do this fill. You cannot enter all these data separately and at the same time in these same fields.

  • @Bruuno Vianna What if in case I remove the clasps would work? Because it would be objects inside the object date.

  • You have a rule problem here. For example, for every cnpjToma you have in the json object, you have only one corresponding in your form. I’ve already prepared a code that solves the issue, but I need more details of how exactly you want to fill in.

  • For example: you can take only one id on that object and populate the data. Thus, each field will have a value within an id. Another example: you can scan all ids in date and popular the form. Only this will leave the fields with the data only of the last id, since the previous ones will normally be overwritten.

  • The problem is not the structure of the data, but how you want to popular this form tendos several possible data for only a corresponding field. Understands?

  • @Brunnovianna Then you would need a condition to show according to the id of Json objects, if id 0 fills the fields with the data of object 0 and so on.

  • Yes, as shown below...

  • @Leandro See my answer and, any doubt, can call me.

  • OK Brunovianna I’ll test here and give you a feedback!

Show 6 more comments

2 answers

1


First, request the json file:

$.ajax({
    url: "nomeDoArquivo.json",
    success: function(data){

    }
});

Save the data somewhere else:

var dados;
$.ajax({
    url: "nomeDoArquivo.json",
    success: function(data){
        dados = data;
    }
});

Then create a function to scroll through the data fields and populate the form fields:

var populateInputs = function(data){
    for (var prop in data){
        var val = data[prop];
        $("#"+prop).val(val);
    };
};

So just use it:

populateInputs(dados[0]);

An important tip: Your original file is badly formatted. For example, in {"id:"0" is not being closed the quotes in id. Another problem is that it opens a new object {"lNeg" without a comma before. This will give parse error.

Change to:

{"data":[
    {"id":"0", "lNeg":"",...}
  • @Brunnoviana mine here didn’t work out dude. I formatted Json like yours. In the console shows the error: Cannot read Property '0' of Undefined.

  • Print the contents of the object that you are passing into populateInputs, please, and glue for me to see.

  • sorry guy didn’t get it. I don’t dominate Json. in case there would be

  • {"id":"0","lNeg":"","cnpjToma":"02.558.157/1001-62","nDoc":"00121961","nPed":"5100484612","dtEmis":"01/11/2016","dtVenc":"01/01/2017","munic":"SÃO PAULO","codNat":"17.06","opts":"","tipoDoc":"","vIcms":"","vDoc":"","irrf":"","inss":"","iss":"","pis":"","cofins":"","cssl":"","Obs":""},

  • please guy doesn’t abandon me :) when I invoke the variable populateInputs(dados[0]); out of function(data) she gives the error Cannot read Property '0' of Undefined, but when calling inside the error function in the console, but, tbm does not populate the inputs;

  • Did you save the ajax response to an external variable as it indicates? See in my code that I started a global variable dados and, within ajax, I assigned it to data, so: dados = data.

  • yes, I edited the question and put your script there.

  • @Leandro Can you make the code available somewhere? I think you are calling populateInputs before the return of the ajax call. We need to see the execution time of your application.

  • The jquery is there in the question just above, I called where you demonstrated.

Show 5 more comments

0

In your case, you take the Object by id and use its attributes to place in the inputs as follows:

$("#cnpjToma").val(objeto[0].cnpjToma)

In js pure:

document.getElementById("cnpjToma").value = objeto[0].cnpjToma

Only this will make your code a little static, if you want to make dynamic or use all objects of the array you will have to create a logic to traverse it and use the attributes of these.

But that’s basically it, the rest is your logic!

Hug!

  • He expects a solution using jQuery as described in the question.

  • Ok, but jQuery = javascript, just use the one that makes jQuery easy and you’re done.

  • Ready now as jquery.

  • I’m sorry, but it’s still not like that. It should be $("#cnpjToma").val(objeto[0].cnpjToma)

  • All right, I don’t know about jQuery, but this kind of questioning can be solved with pure js, and for those who know jQuery just convert. And I don’t prefer to give ready-made answers, I like people to take a hint and look for knowledge so they can fix knowledge. But is in charge of each right. thanks

  • Alias, I used your comment to fix the code :) thanks for the tip.

  • I agree with you. Using pure js in this case would be much better. However, I am following the OS rules in respecting the question request. You could suggest using pure javascript as a better-than-requested solution. ;)

  • Now it’s cool!

Show 3 more comments

Browser other questions tagged

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