How to copy class values to another class in Javascript?

0
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Protipo Software de Evento</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script></head><body><pid="demo" style="font-family:courier"></p>
<form style="background-color: gray;" action="" method="post" id="formulario">
<input  type="button" id="novoProd" value="Novo serviço" />
<input type="submit" value="Enviar" onclick="myReport()"/>
Valor total do evento é de R$
<p style="display:inline; color:yellow"id="result"></p>
<p class="demo"></p>
<div id="item" class="item">

<!-- Serviços -->
<label>Selecione o(s) serviço(s) para o seu evento:</label>
<select name="produtoId[]">
<option value="Buffet1">Buffet 1</option>
<option value="Decoração1">Decoração 1</option>
<option value="Transporte1">Transporte 1</option>
</select>

<!-- TOTAL de custos -->
<input type="number" class="qtd" onchange="myTotal()">

<!-- TOTAL de cada LINHA -->
<!-- <table style="display:inline"><th>R$</th></table> -->
<p style="display:inline" class='til'></p>
</div>

</form>
<!-- Calcula o TOTAL -->
<script>
function myTotal() {
var total = 0;
var total2 = 0;
var x = document.getElementsByClassName("qtd");
var i;
for (i = 0; i < x.length; i++) {
total = total + parseInt(x[i].value);
total2 = parseInt(x[i].value);
}
document.getElementById("result").innerHTML = total;
document.getElementsByClassName("til")[0].innerHTML = total2;
}
</script>

<script type="text/javascript">
$(document).ready(function() {
$("#novoProd").click(function() {
var novoItem = $("#item").clone().removeAttr('id');
novoItem.children('input').val(''); //limpa o campo quantidade
$("#formulario").append(novoItem);
});
});
</script>
</body>
</html>


The script tries: Home Bring the value of class "qtd" to "til" by CLASS (Here it works) Home How to follow the "qtd" Class Array with the "til" CLASS?

    
asked by anonymous 03.12.2018 / 02:11

1 answer

1

The function getElementsByClassName as the name says returns Elements or is a kind of Array called HTMLCollection .

In your code you are working as a HTMLElement ( trying to access .innerHTML ) when in fact it is an array of HTMLElements

Possible solution: document.getElementsByClassName("til")[0].innerHTML

Another thing I noticed is that you 'typing' the value in HTML while still calculating, ie within for

function myTotal() {
    var total = 0;
    var total2 = 0;
    var x = document.getElementsByClassName("qtd");
    var i;

    for (i = 0; i < x.length; i++) {
        total = total + parseInt(x[i].value);
        total2 = parseInt(x[i].value);
    }
    document.getElementById("result").innerHTML = total;
    document.getElementsByClassName("til")[0].innerHTML = total2;
}
    
03.12.2018 / 02:34