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.
First you cannot set the attribute
id
of an element within a loop. The attributeid
defines a single element on the page and, if there are several with sameid
, 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.– Woss