For each field that is created add a value

Asked

Viewed 24 times

0

Hello I am trying to create inputs and in them I would like to put the values that have in my array.

 <div id="guias">
    <div class="form-row">
        <div class="col-md-6 mb-3" id="origem">
            <label for="Email">Email: </label>
            <input type="text" name="Email[]" id="Email" class="form-control"
                placeholder="Ex: [email protected]">
            <div class="invalid-feedback">

            </div>
        </div>
    </div>

    <div id="destino" class="form-row"></div>
</div>

<script>
    **const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];**

    console.log("Meu array: " + array);

    for (i = 0; i < array.length; i++) {

        var clone = document.getElementById('origem').cloneNode(true);
        var destino = document.getElementById('destino');
        destino.appendChild(clone);

        var camposClonados = clone.getElementsByTagName('input');

        camposClonados[i].value = array[i];
    }

</script>

But the result is giving so:

Resultado

He is only putting in a single field and is not creating the others, and besides not putting in the first input this putting in the second.

Could someone help me.

1 answer

1


Why not assign value to the element that was cloned before making the append? This will already add the ready element, and in addition, you can declare the variable "destination" only once before the for:

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log("Meu array: " + array);

var destino = document.getElementById('destino');

for (i = 0; i < array.length; i++) {
    var clone = document.getElementById('origem').cloneNode(true);
    // encontra o primeiro "input" com a classe "form-control" a partir do elemento clonado e muda o seu valor
    clone.querySelectorAll("input.form-control")[0].value = array[i];        
    destino.appendChild(clone);
}
 <div id="guias">
    <div class="form-row">
        <div class="col-md-6 mb-3" id="origem">
            <label for="Email">Email: </label>
            <input type="text" name="Email[]" class="form-control"
                placeholder="Ex: [email protected]">
            <div class="invalid-feedback">

            </div>
        </div>
    </div>

    <div id="destino" class="form-row"></div>
</div>

  • So I’d like to put from the first

  • "For each field that is created add a value" then the title of the question is wrong :) Pq does not remove the first item of the array then and already puts it in the first field?

  • Ha yes I managed to put.

  • Thank you for helping :)

Browser other questions tagged

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