Read Javascript on all ForEach items

1

Well, I have a foreach that loads several inputs, and I want my javascript code to read on all the inputs generated by foreach, can anyone give me a hint how to do it?

Example

<c:forEach items="${listaServico}" var="lista"

<input id="txt1" type="text"  onkeyup="calcular()">
<input id="txt2" type="text"  onkeyup="calcular()">
<input id="result" type="text"">

</c:forEach>

JAVASCRIPT

<script type="text/javascript">

function calcular(){


    var valor1 = parseFloat(document.getElementById('txt1').value, 10);
    var valor2 = parseFloat(document.getElementById('txt2').value, 10);
    document.getElementById('result').value = valor1 * valor2;
}

</script>

It is to calculate the value of the first input and the second and throw in the third input.

The problem is that only loads JavaScript in the first item of forEach, the rest does not work JavaScript.

If anyone can help me, I would appreciate it.

    
asked by anonymous 26.07.2017 / 03:33

1 answer

0

Just as Anderson already mentioned, it is imperative to change id to class , since we can not have id 's repeated on a page. So the initial html generation part should be:

<c:forEach items="${listaServico}" var="lista"

<input class="txt1" type="text"  onkeyup="calcular()"><!-- class="txt1" em vez de id-->
<input class="txt2" type="text"  onkeyup="calcular()">
<input class="result" type="text"">

</c:forEach>

In javascript we can now do the calculation of each pair of elements using the function to get all of a class getElementsByClassName and a for :

function calcular(){
    var valores1 = document.getElementsByClassName('txt1'); //lista de todos os valores1
    var valores2 = document.getElementsByClassName('txt2'); //lista de todos os valores2
    var resultados = document.getElementsByClassName('result'); //lista de resultados

    for (let i = 0; i < valores1.length; ++i){ //para cada conjunto
        let num1 = parseFloat(valores1[i].value); //ir buscar o 1º valor como float
        let num2 = parseFloat(valores2[i].value); //ir buscar o 2º valor como float
        resultados[i].value = num1 * num2; //calcular e apresentar no resultado respetivo
    }
}
    
26.07.2017 / 13:48