Create input fields according to the size of an array

Asked

Viewed 189 times

1

Good evening, I’m receiving via JSON a List with the structure below:

anexo: [{cod: 5, nome: "anexo1.pdf"}, {cod: 6, nome: "texto.txt"}]

And I use the function below:

$.getJSON(url + cod,
                    function (ajax) {
                        for (var i = 0; i < ajax.anexo.length; i++) {
                            //alert(ajax.anexo[i].nome);
                            $.each(ajax.anexo[i], function (k, value) {
                                $("#formAnexo").find($('[name="anexo.' + k + '"]')).each(function () {
                                    setElementValue(this, value, 'anexo.' + k);
                                });
                            });

                        }
                    });

This function fetches the JSON data and fills the <textarea> of my form. In the case of only one item, it is working. Now if there are 2 or more items, like the structure I presented at the beginning, only one data is appearing in the form (the last one overwrites the previous ones - from what I understood).

My form is like this:

<label>Anexo:</label>
<textarea rows="5" id="nome" readonly="nome" name="anexo.nome" ></textarea>

How can I fix this so that my JSON has a List of 2 or more items, and these shall be added to textarea?

  • Your form has a single textarea or several (in other words, it’s for the name of each item to end up in a different textarea, or for all of them to go to the same textarea, separated by spaces or line breaks for example)? Is there an element with the name anexo.cod? And what setElementValue ago?

1 answer

1


There are some problems with your code:

  1. First you iterate on the JSON elements, then you iterate on the estates of each element; in my opinion, it would be enough to iterate on the elements, not?

    for (var i = 0; i < ajax.anexo.length; i++) { // Itera sobre os elementos
    
        //alert(ajax.anexo[i].nome); // Isso me parece correto
    
        $.each(ajax.anexo[i], function (k, value) { // Itera sobre o elemento?
            // k == "cod", value == 5
            // k == "nome", value == "anexo1.pdf"
    
  2. The selector '[name="anexo.' + k + '"]' will select all the elements with the name anexo.nome (and anexo.cod), no matter what external loop iteration you are in. So yes, subsequent elements will overwrite previous ones.

  3. The method find accepts a selector, an element, or a jQuery object. This is correct:

    $("#formAnexo").find($('[name="anexo.' + k + '"]')).each
    

    but it’s simpler to do:

    $("#formAnexo").find('[name="anexo.' + k + '"]').each
    

The correct way to do it depends on your intention. It was not clear in the question whether there is a single textarea or several, but for what has been exposed I will assume that it is only one. In that case, I suggest to accumulate the names in a list, and at the end assign them at once:

var ajax = { anexo: [{cod: 5, nome: "anexo1.pdf"}, {cod: 6, nome: "texto.txt"}] };

var nomes = [];
for (var i = 0; i < ajax.anexo.length; i++) {
  nomes.push(ajax.anexo[i].nome);
}

$("#formAnexo").find('[name="anexo.nome"]').each(function() {
  this.value = nomes.join("\n");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formAnexo">
  <label>Anexo:</label>
  <textarea rows="5" id="nome" readonly="nome" name="anexo.nome" ></textarea>
</form>

  • mgibson, I think I better then put everything inside the textarea. How should I do then following this your logic?

  • @The example I gave places the names of all the items in the textarea, one per line. Do you want to put the codes in too, or something else? (e.g., some formatting...) By the way, you don’t accurate wear a textarea only, it is possible (simple until) to create a dynamic form where the number of components is variable, depending on the number of items. But for that we must determine first what you will do with this data, i.e. when you send them back to the server (if it goes) as they will be treated there.

  • was exactly how I needed it. Thank you very much!

Browser other questions tagged

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