1
have a question?! on the link below:
jQuery1.7.2 compatibility issue for jQuery 3.3.1
i have a code that calculates some inputs based on price, quantity, subtotal (price * quantity) and overall total (sum of inputs subtotals), as an example below:
It turns out that I would like to hide all inputs and go showing as I click on a button, to add new products (inputs). I did based on the project:
Add / remove fields dynamically
However, as inputs are generated in JS I could not make it work. Could someone help me? Is it possible?
Follow my example:
<!doctype html>
<html lang="pt-br">
<head>
</head>
<body>
<script src="https://code.jquery.com/jquery-1.7.2.js" ></script>
<form name="form1" action="" method="post">
<script type="text/javascript">
//Total máximo de campos que você permitirá criar em seu site:
var totalCampos = 10;
//Não altere os valores abaixo, pois são variáveis controle;
var iLoop = 1;
var iCount = 0;
var linhaAtual;
function AddCampos() {
var hidden1 = document.getElementById("hidden1");
var hidden2 = document.getElementById("hidden2");
//Executar apenas se houver possibilidade de inserção de novos campos:
if (iCount < totalCampos) {
//Limpar hidden1, para atualizar a lista dos campos que ainda estão vazios:
hidden2.value = "";
//Atualizando a lista dos campos que estão ocultos.
//Essa lista ficará armazenada temporiariamente em hidden2;
for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
if (document.getElementById("linha"+iLoop).style.display == "none") {
if (hidden2.value == "") {
hidden2.value = "linha"+iLoop;
}else{
hidden2.value += ",linha"+iLoop;
}
}
}
//Quebrando a lista que foi armazenada em hidden2 em array:
linhasOcultas = hidden2.value.split(",");
if (linhasOcultas.length > 0) {
//Tornar visível o primeiro elemento de linhasOcultas:
document.getElementById(linhasOcultas[0]).style.display = "block"; iCount++;
//Acrescentando o índice zero a hidden1:
if (hidden1.value == "") {
hidden1.value = linhasOcultas[0];
}else{
hidden1.value += ","+linhasOcultas[0];
}
/*Retirar a opção acima da lista de itens ocultos: <-------- OPCIONAL!!!
if (hidden2.value.indexOf(","+linhasOcultas[0]) != -1) {
hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
}else if (hidden2.indexOf(linhasOcultas[0]+",") == 0) {
hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
}else{
hidden2.value = "";
}
*/
}
}
}
function RemoverCampos(id) {
//Criando ponteiro para hidden1:
var hidden1 = document.getElementById("hidden1");
//Pegar o valor do campo que será excluído:
var campoValor = document.getElementById("valor_unitario"+id).value;
//Se o campo não tiver nenhum valor, atribuir a string: vazio:
if (campoValor == "") {
campoValor = "vazio";
}
if(confirm("O campo que contém o valor:\n» "+campoValor+"\nserá excluído!\n\nDeseja prosseguir?")){
document.getElementById("linha"+id).style.display = "none"; iCount--;
//Removendo o valor de hidden1:
if (hidden1.value.indexOf(",linha"+id) != -1) {
hidden1.value = hidden1.value.replace(",linha"+id,"");
}else if (hidden1.value.indexOf("linha"+id+",") == 0) {
hidden1.value = hidden1.value.replace("linha"+id+",","");
}else{
hidden1.value = "";
}
}
}
</script>
<script type="text/javascript">
function id( el ){
//return document.getElementById( el );
return $( el );
}
function calcTotal( un01, qnt01 )
{
return un01 * qnt01;
}
function getElementParent(event){
return event.srcElement.parentNode.parentNode.getAttribute('id');
}
function getValorUnitario(elParent){
return $('#'+elParent+' .class_unit input').val();
}
function getQuantidade(elParent){
return $('#'+elParent+' .class_quant input').val();
}
function setFieldTotal(elParent, valueUnit, valueQuant){
id('#'+elParent+' .class_total input').val(calcTotal( valueUnit , valueQuant));
setTotalFinal();
}
function setTotalFinal(){
var total = 0;
$('#table-shop div .class_total input').each(function(){
if(this.value != ''){
var valor = this.value;
total += parseInt(valor);
}
});
$('#total .value_total').html(total);
$('#total .value_total').val(total);
}
$(document).ready(function(){
id('#table-shop div .class_unit').keyup(function(event)
{
var elemenPai = getElementParent(event);
var valueUnit = getValorUnitario(elemenPai);
var valueQuant = getQuantidade(elemenPai);
setFieldTotal(elemenPai, valueUnit , valueQuant);
});
id('#table-shop div .class_quant').keyup(function(event)
{
var elemenPai = getElementParent(event);
var valueUnit = getValorUnitario(elemenPai);
var valueQuant = getQuantidade(elemenPai);
setFieldTotal(elemenPai, valueUnit , valueQuant);
});
});
</script>
<script type="text/javascript">
//Escrevendo o código-fonte HTML e ocultando os campos criados:
for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
document.write("<span id='linha"+iLoop+"' style='display:none'><div class='class_unit'>Valor Unitário "+iLoop+":<input type='text' name='valor_unitario"+iLoop+"' id='valor_unitario"+iLoop+"' /></div><div class='class_quant'>Quantidade "+iLoop+": <input type='text' name='qnt"+iLoop+"' id='qnt"+iLoop+"' value='0' /></div><div class='class_total'>SubTotal "+iLoop+": <input type='text' name='total"+iLoop+"' id='total"+iLoop+"' readonly='readonly' /></div> <input type='button' value='Remover' onclick='RemoverCampos(\""+iLoop+"\")'></span>");
}
</script>
<div id="total">Total: <span class="value_total"></span> </div>
<div id="total">Total: <input class="value_total" readonly></input> </div>
<br><br><br>
<input type="button" value="Adicionar campos" onclick="AddCampos()">
<br><br><input type="text" name="hidden1" id="hidden1">
<input type="hidden" name="hidden2" id="hidden2">
</form>
</body>
</html>
I happen to be able to show/hide inputs, but you don’t know! Thank you very much.
Could you add your code to the question? You can use the snippet (button
</>
editor) to show working.– Woss
If you provide the code becomes easier to find the problem
– Otavio Souza Rocha
By the logic of what you need, Unit value, quantity and subtotal needs to be done via javascript? You might think about leaving these fixed inputs to fill and pass the filled value to the new field when submitted and then after each submition is calculated the total and if the total is zero nothing appears and other conditions can be made, if you do not have Uniario value no quantity or subtotal appears and when quantity is 0 no subtotal appears.
– Eduardo
So...this is an auto mechanical service system, and as you put the parts to be used, the system is already calculating. in this case I need to track how expensive the 'purchase' is getting to be able to pass to the customer or review some item, before closing the production order and give low in the system. I accept any suggestion!
– Nosredna