Read Javascript on all Foreach items

Asked

Viewed 284 times

1

Guys, I have a foreach that loads several inputs, and I want my javascript code read on all inputs generated by foreach, someone can give me a tip on how to do ?

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 input and to input the third input.

The problem is that only loads Javascript in the first foreach item, the rest does not work Javascript.

If anyone can help me, I’d really appreciate it.

  • 2

    First you cannot set the attribute id of an element within a loop. The attribute id defines a single element on the page and, if there are several with same id, the browser will ignore. So only the first one works, as it will be unique. The way HTML is structured may make it complicated to do what you need.

1 answer

1

As Anderson has already mentioned, it is imperative to exchange id for class, because we are not allowed to have id's repeated on a page. Therefore the initial generation part of html 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 calculate each pair of elements using the function to fetch 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
    }
}

Browser other questions tagged

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