I need to add a cell phone of an html table dynamically

Asked

Viewed 520 times

0

Hello I’m with a code I would like it to sum between the cells of a table and display below in total according to the code below.

-more would like dynamically as you add another column below the products without having to change the javascript.

Follow my example code, someone give this hanging here to friend already thank ! `

 
      
      
      var confirma = document.getElementById("btn-confirma");
      var cancela = document.getElementById("btn-cancela");
      var enviar = document.getElementById("btn-enviarpedido");
      var formulario = document.getElementById("formulario");

      var snack = document.getElementById("snack");
      var load = document.getElementById("load");
      var cadastro = document.getElementById("cadastro");

      var soma_13 = document.getElementById("soma-13");
      var subtrai_13 = document.getElementById("subtrai-13");
    
      var soma_8 = document.getElementById("soma-8");
      var subtrai_8 = document.getElementById("subtrai-8");
      var nome;
      var fone;

      

      var intervalo;
      var qtdade_8 = 0;
      var qtdade_13 = 0;
      var preco_13= 54.10;
      var preco_8 = 17.20;
      var total = 0.00;
      
      (function(){
         document.getElementById("preco-8").innerHTML = "R$ " + preco_8.toFixed(2).replace('.',',');
         document.getElementById("preco-13").innerHTML = "R$ " + preco_13.toFixed(2).replace('.',',');
      })();

      soma_13.addEventListener("click", function(){
         qtdade_13 = qtdade_13 + 1;
            AtualizaDados();
      },false );

      subtrai_13.addEventListener("click", function(){
        if(qtdade_13 > 0) qtdade_13 = qtdade_13 - 1;
            AtualizaDados();
      },false );

      soma_8.addEventListener("click", function(){
         qtdade_8 = qtdade_8 + 1;
            AtualizaDados();
      },false );

      subtrai_8.addEventListener("click", function(){
         if(qtdade_8 > 0) qtdade_8 = qtdade_8 - 1;
          AtualizaDados();
      },false );
      
      
      confirma.addEventListener("click", function(){
         //snack.className = 'confirmacao animation-snack';
         nome =  document.getElementById("nome").value;
         fone =  document.getElementById("telefone").value;

		 
		 
		
         
                  document.getElementById("qtd-13").value = qtdade_13;
                  document.getElementById("qtd-8").value = qtdade_8;
                  document.getElementById("pre-13").value = preco_13;
                  document.getElementById("pre-8").value = preco_8;
                  document.getElementById("tot").value = total;
               cadastro.style.display = "none";
               load.style.display = "block";
               load.className = 'loading animation-load';

               intervalo = setInterval(function(){
                  finalizaPedido();
               },3000);


      },false );

      enviar.addEventListener("click", function(){
         console.log(load);
         cadastro.style.display = "block";
      },false );

      cancela.addEventListener("click", function(){
         cadastro.style.display = "none";

      },false );

function fone(campo){
         if (campo.value.length == 0){
         campo.value = "(" + campo.value; }
         if (campo.value.length == 3){
         campo.value = campo.value + ") "; }
         if (campo.value.length == 10){
         campo.value = campo.value + "-";}
      }

function finalizaPedido(){
   clearInterval(intervalo);
   console.log("Finalizando");
   load.className ='loading animation-load-back';
   snack.className = 'confirmacao animation-snack';
   enviar.style.display ="none";
   document.getElementById("check").innerHTML  = " <img src='check_256.png'  style='width: 40px;height: 40px;'/>";
  
   formulario.submit();
}

function AtualizaDados(){
      document.getElementById("qtdade-13").innerHTML = qtdade_13;
      document.getElementById("qtdade-8").innerHTML = qtdade_8;

      total = (qtdade_8 * preco_8) + (qtdade_13 * preco_13);
      document.getElementById("soma-total").innerHTML = total.toFixed(2).replace('.',',');

 }
*{
	font-family: "sans-serif";
	padding: 0px;
	margin: 0px;
}
html{
	height: 100%;
}
body{
	
	min-height: 100%;
    display: flex;
    flex-direction: column;
}

h1{
	font-family: "sans-serif";
	font-size: 18px;
	color: #FFFFFF;
	font-weight: 700;
	vertical-align: middle;
	text-align: center;
	/*text-shadow: 0 -1px 0 #000;*/
}
.header{
  background: #212121;
  width: 100%;
  height: 40px;
  padding-top: 20px;
}
.content{
	background: #F5F5F5;
	flex: 1;
}

.content table tr td{
	/*border: 1px solid #000;*/
}

.footer{
  background: #212121;
  height: 120px;
  z-index: 1;
}
.style1{
	color: #FFF;
	font-size: 23px;
	font-weight: 700;
}
.style2{
	color: #FFF;
	font-size: 10px;
	text-align: center;
	text-shadow: 0 -1px 0 #FFF;	

}
.style3{
	color: green;
	font-size: 15px;
	text-align: center;
	text-shadow: 0 -1px 0 #FFF;		
	font-weight: 700;	
}
.style4{
	color: #212121;
	font-size: 15px;
	text-align: center;
	text-shadow: 0 -1px 0 #000;	
	padding: 7px;
}
.ui-btj table{
	width: 100%;
	padding-left: 10px; 
	padding-right: 10px; 
}
.ui-btj table tr td{
	height: 50px;
	margin: 2px;
	background: #e3e3e3;
}

.footer table td{
	padding: 10px;
	vertical-align: middle;
}
.ui-btn-corner{
	height: 40px;
	margin: 0px;
	padding: 5px;

}

.ui-btn{
	background: #FEDE02;
	padding: 7px 10px 7px 10px;
	display: inline-block;
	border-radius: 10px;
	cursor: pointer;
}
.ui-btn:hover{
	background: #FEA002;
}

.ui-btn-up{
	background: #F5F5F5;
	padding: 7px 20px 7px 20px;
	border-radius: 10px;
	vertical-align: middle;
	text-align: center;
	border: 3px solid #ccc;
	font-size: 20px;
	cursor: pointer;
}

.ui-btn-up:hover{
	background: #FEDE02;
}

li{
	
	background: #eBeBeB;
	margin-bottom: 2px;
	line-height: 7px;
	padding-bottom: 5px;
	border-bottom:1px solid #ddd ;
}
img{
	width: 65px;
	height: 90px;
	vertical-align: middle;
	padding: 5px;
}

.btj-comando{
	min-width: 90px; 
}
.btj-comando table{
	height: 100%;
	width: 100%;
}
.btj-comando table tr td{
	height: 15px;
}

.circle {
  width: 50px;
  height: 50px;
  border-radius: 40px;
  box-sizing: border-box;
  border: solid 6px rgba(255, 255, 255, 0.2);
  border-top-color: #989898;
  animation: spin 1s infinite linear;
  margin-left: 70px;
  margin-top: 15px;

}
@keyframes spin { 
  100% { 
    transform: rotate(360deg); 
  } 
} 

.loading{
	width: 200px;
	height: 110px;
	background: #dedede;
	position: absolute;
	padding: 5px;
	border-radius: 10px;
	border: solid 1px rgba(255, 255, 255, 0.2);
	left:20%;
	top: 25%;
	-webkit-box-shadow: -0px 0px 32px 0px rgba(0,0,0,0.45);
	-moz-box-shadow: 0px 0px 32px 0px rgba(0,0,0,0.45);
	box-shadow: 0px 0px 32px 0px rgba(0,0,0,0.45);
	display: none;
	overflow: hidden;
	
}

.form{
margin:0% 0% 0% 20%;

	width: 200px;
	height: 130px;
	background: #dedede;
	position: absolute;
	padding: 10px;
	border-radius: 5px;
	border: solid 1px rgba(255, 255, 255, 0.2);
	top: 25%;
	-webkit-box-shadow: -0px 0px 22px 0px rgba(0,0,0,0.45);
	-moz-box-shadow: 0px 0px 22px 0px rgba(0,0,0,0.45);
	box-shadow: 0px 0px 22px 0px rgba(0,0,0,0.45);	
	display: none;
}
#cadastro table tr td{
	height: 25px;
	padding: 0px;
}
.ui-btn-form{
	color: #525252;
	vertical-align: bottom;
	cursor: pointer;
}

.confirma:hover{
	color: blue;
}
.cancela:hover{
	color: red;
}
.form input{
	margin: 0px;
}
label{
	font-size: 12px;
	display: inline-block;
}
.confirmacao{
	width: 300px;
	height: 30px;
	background: #525353;
	position: absolute;
	padding: 20px 10px;
	border-radius: 5px;
	border: solid 1px rgba(255, 255, 255, 0.2);
	top: 60%;
	-webkit-box-shadow: -0px 0px 55px 0px rgba(0,0,0,0.25);
	-moz-box-shadow: 0px 0px 55px 0px rgba(0,0,0,0.25);
	box-shadow: 0px 0px 55px 0px rgba(0,0,0,0.25);	
	color: #FFFFFF;
	font-weight: 700;
	display: none;
}
.animation-snack{
	display: block;
	animation-duration: 2s;
	animation-name: slideup;
}


.animation-load-back{
	display: block;
	-webkit-animation: slidedownload 1s forwards;
     animation: slidedownload 1s forwards;
}

input{
	height: 20px;
}
@keyframes slideup{
	from{
		top: 100%;
	}
		to{
		 top: 60%;	
		}
}

@keyframes slideupload{
	from{
		top: 100%;
	}
		to{
		  top: 40%;
		}
}

@keyframes slidedownload{
	from{
		top: 40%;
	}
		to{
		  top: 100%;
		  display: none;
		}
}

.error{
	position: absolute;
	left: 30%;
	color: red;
	font-size: 10px;
}
<body>
  <div class="header">
      <h1 >PEDIDO DE GAS</h1>
  </div>
  <div class="content">
     <ul>
       <li>
          <table>
            <tr>
              <td >
                  <img src="13.png" alt="">      
              </td>
             <td  width="80%" class="ui-btj">
                 <table>
                    <tr>
                      <td align="center" ><span class="style3">13kg</span></td>
                    </tr>
                    <tr>
                      <td align="center"><span class="style4" id="preco-13">R$ 0,00</span></td>
                    </tr>
               </table>

                
              </td>
              <td  class="btj-comando">
                  <table>
                    <tr>
                      <td class="ui-btn-up" id="soma-13">+</td>
                    </tr>
                    <tr>
                      <td class="style4" id="qtdade-13">0</td>
                    </tr>
                    <tr>
                      <td class="ui-btn-up" id="subtrai-13" >-</td>
                    </tr>
                  </table>
                
              </td>
            </tr>
          </table>
          
          
       </li>
       <li>
          <table>
            <tr>
              <td >
                  <img src="8.png" alt="">      
              </td>
             <td  width="80%" class="ui-btj">
                 <table>
                    <tr>
                      <td align="center" ><span class="style3">8kg</span></td>
                    </tr>
                    <tr>
                      <td align="center"><span class="style4" id="preco-8">R$ 0,00</span></td>
                    </tr>
               </table>

                
              </td>
              <td class="btj-comando">
                  <table>
                    <tr>
                      <td class="ui-btn-up" id="soma-8">+</td>
                    </tr>
                    <tr>
                      <td class="style4" id="qtdade-8">0</td>
                    </tr>
                    <tr>
                      <td class="ui-btn-up" id="subtrai-8">-</td>
                    </tr>
                  </table>
                
              </td>
            </tr>
          </table>
          
          
       </li>
       
     </ul>
  </div>

<div class="loading" id="load">
  
        <div class="circle"></div>
          <div align="center"><br>
              <span>Processando seu Pedido</span>
          </div>
</div>

<form id="formulario" action="teste.php" method="post">
  <div class="form" id="cadastro">
      <input type="hidden" id='qtd-13' name='qtd-13' value="teste1">
      <input type="hidden" id='pre-13' name='pre-13'>
      <input type="hidden" id='qtd-8' name='qtd-8'>
      <input type="hidden" id='pre-8' name='pre-8'>
       <input type="hidden" id='tot' name='tot'>
      <table >
        <tr>
          <span class="error" id="error"></span>
        </tr>
        <tr >
         
          <td colspan="2">
            <label for="nome">Nome</label>  
            <input type="text" id="nome" name="nome" placeholder="Nome Completo" >
          </td>

        </tr>
        
        
        <tr>
          <td colspan="2">
            <label for="telefone">Fone</label> 
             <input placeholder="(97) 9999-9999" name="telefone" onkeypress="fone(this);" maxlength="16" type="text"  id="telefone">
          </td>
        </tr>
        <tr>
          <td class="ui-btn-form cancela" align="center" id="btn-cancela">Cancela</td>
          <td class="ui-btn-form confirma" align="center" id="btn-confirma">Confirma</td>
        </tr>
      </table>
  </div>
</form>
  <div class="confirmacao" id="snack">
  
          <span>Pedido Enviado Com sucesso...</span>
  </div>

  <footer class="footer">
      <table width="100%">
        <tbody>
            <tr>
              <td width="49%">
                <div align="center">
                  <span class="style1">TOTAL</span>
                </div>
              </td>
              <td width="51%">
                  <div align="center" class="style2">
                    ENTREGAMOS ATÈ AS 18:00 HS
                  </div>
              </td>
            </tr>
             <tr>
              <td width="49%">
                <div align="center">
                  <span class="style1">R$</span>
                   <span class="style1" id="soma-total">0,00</span>
                </div>
              </td>
              <td width="51%" id="check" align="center">
                    <div align="center" class="ui-btn-corner">
                      <span class="ui-btn" id="btn-enviarpedido">
                        <span>
                           Enviar Pedido
                        </span>
                        
                       </span>
                    </div>
                   
              </td>
            </tr>           
        </tbody>
      </table>
  </footer>
</body>

`

  • What exactly do you want to add up? It wasn’t very clear.

  • This I change only one more row or be another product only in the table without having to change the javascrtip

  • 1

    Suggestion, try to write your question better. You posted apparently all your code, but were not at all accurate as to the problem.

  • because the products and values come from my database understood

  • I’m sorry I’ll change and because I don’t know much about jquery or javascript !

  • I couldn’t understand it. I recommend clicking "edit" on your question, and in no hurry, explain from the beginning what your application does exactly, what it should do and doesn’t do, how summing up table cells will help you exactly, what cells you want to add up and when you want to add up.

  • Okay I’m checking how to ask the most direct question since you already gradeco for helping me

  • OK changed I hope very much you understand me !

  • I would like to add as I add more and less of each product in the list

  • But isn’t it working anymore? I clicked on the code posted in your question and apparently it’s working.

  • that this run more and more every time I go to add a new product and necessary that I change the javascript, I need it to be dynamic because I will fetch the information coming from a database in a list.

  • It’s gonna take a lot of altering that code to get dynamic. Starting with the price of products that instead of variables should be in an array or JSON object. Second you will have to create a single function for the event to add products from any button. Use the "date" attribute on the button and add the product identifier there. So you can recover in Event....

  • I recommend you take a look at a basic Jquery tutorial as it will make your life much easier.

  • The code I got in Control C rsrs more as I don’t know much of jquery will be next since I already thank you all for your work I have to study more thank you I will put as solved

  • Still waiting for a light at the end of the tunnel

Show 10 more comments

1 answer

2


Comrade, follow a base to help you. I understood your idea of not having to edit the java-script, so it was necessary to concatenate an id with a fixed name to detect the html ids used.

When you generate html with php(inside a loop by grabbing id, product name and price ):

        <!-- Bloco gerado por PHP -->
        <tr>
            <td class="prodtd">

                <div id="nome<?php echo $id; ?>"  class="nomeprod"> <?php echo $nome_produto; ?></div>

                <div id="preco<?php echo $id; ?>" class="preco">    <?php echo $preco; ?></div>

            </td>
            <td align="center" valign="middle">

                <input type="button" value="-" onclick="remove(<?php echo $id; ?>)"> 

                <span id="qtd<?php echo $id; ?>">0</span> 

                <input type="button" value="+" onclick="adiciona(<?php echo $id; ?>)">

            </td>
        </tr>
        <!-- Fim Bloco gerado por PHP -->

Below follows example code working:

// java-script

total = 0;
        
        function adiciona(id)
        {
            calcula(id,"adicao");
        }
        
        function remove(id)
        {
            calcula(id,"subtracao");
        }    
            
        function calcula(id,operacao)
        {
                nomeid  = "nome"+id;
                precoid = "preco"+id;
                qtdid   = "qtd"+id;
                
                nome  = document.getElementById(nomeid).innerHTML;
                
                preco = document.getElementById(precoid).innerHTML;    
                preco = parseInt(preco);
                
                qtd   = document.getElementById(qtdid).innerHTML;
                qtd   = parseInt(qtd);

                //Debug
                //alert("Produto: " + nome + "\n Preço: " + preco);    
                
                if(operacao=="adicao")
                {
                    total = total + preco;
                    qtd = qtd + 1;
                }
                else
                {
                    total = total - preco;
                    qtd = qtd - 1;
                }
                
                document.getElementById(qtdid).innerHTML = qtd;
                
                document.getElementById("total").innerHTML = total;
        }    
     
/* css */
        div {text-align:center;}
        table {  border-collapse: collapse; border:1px solid #777; width:500px; margin:auto; }
        .prodtd { width:380px; height:80px; }
        .nomeprod { background-color:#ffa;}
        .preco { background-color:#eee;}
    <body>

        <table>
        
            <!-- Bloco gerado por PHP -->
            <tr>
                <td class="prodtd">
                
                    <div id="nome1"     class="nomeprod">Nome Prod 1</div>
                    
                    <div id="preco1" class="preco">10</div>
                    
                </td>
                <td align="center" valign="middle">
                
                    <input type="button" value="-" onclick="remove(1)"> 
                    
                    <span id="qtd1">0</span> 
                    
                    <input type="button" value="+" onclick="adiciona(1)">
                    
                </td>
            </tr>
            <!-- Fim Bloco gerado por PHP -->
            
            
            
            <!-- Bloco gerado por PHP -->
            <tr>
                <td class="prodtd">
                
                    <div id="nome2"     class="nomeprod">Nome Prod 2</div>
                    
                    <div id="preco2" class="preco">22</div>
                    
                </td>
                <td align="center" valign="middle">
                
                    <input type="button" value="-" onclick="remove(2)"> 
                    
                    <span id="qtd2">0</span> 
                    
                    <input type="button" value="+" onclick="adiciona(2)">
                    
                </td>
            </tr>
            <!-- Fim Bloco gerado por PHP -->        
            
            <tr>
                <td align="center"><b>Total: <span id="total">0<span></b></td>
                <td>&nbsp;</td>
            </tr>
            
        </table>
        


    </body>

To collect the values and move to PHP:

<script>
    function verifica_e_envia()
    {
        array_dados = new Array();

        colecao = document.getElementsByTagName("tr");

        qtd_blocos = colecao.length - 1; // O último tr da tabela é onde fica o total e está sendo descontado
        // É necessário saber a quantidade de blocos para poder usar em um loop catando os valores

        // Percorre os blocos catando nomes, quantidades e valores dos produtos com quantidade maior que zero
        for(i=1; i<=qtd_blocos ;i++)
        {
            qtdid = "qtd"+i;
            qtd   = document.getElementById(qtdid).innerHTML;
            qtd   = parseInt(qtd);

            if(qtd>0)
            {
                obj_tmp = {};

                nomeid = "nome"+i;
                nome   = document.getElementById(nomeid).innerHTML;

                precoid = "preco"+i;
                preco   = document.getElementById(precoid).innerHTML;
                preco   = parseInt(preco);

                obj_tmp.nome  = nome;
                obj_tmp.preco = preco;
                obj_tmp.qtd   = qtd;
                obj_tmp.subtotal = qtd*preco;

                // adiciona elemento no array de dados que será enviado
                array_dados.push(obj_tmp);
            }
        }

        // põe o array_dados no input hidden json_dados
        document.getElementById("json_dados").value = JSON.stringify(array_dados);

        // envia o formulário form_pedido_produtos
        document.getElementById("form_pedido_produtos").submit();

    }
</script>        

<form action="pedido_produtos.php" method="post" id="form_pedido_produtos" >
    <input type="hidden" name="json_dados" id="json_dados">        
    <input type="button" value="Verifica e envia valores" onclick="verifica_e_envia()">
</form>

To read the data in PHP (pedido_produtos.php):

<?php

if(!isset($_POST["json_dados"])) die("Post não enviado.");

$array_dados = json_decode($_POST["json_dados"]);

//var_dump($array_dados);

$total = 0;

foreach($array_dados as $obj)
{
    echo 'Nome: '. $obj->nome . '<br>';
    echo 'Preço: '. $obj->preco . '<br>';    
    echo 'Quantidade: '. $obj->qtd . '<br>';        
    echo 'Subtotal: '. $obj->subtotal . '<br>';    

    echo '<br><br>';

    $total = $total + $obj->subtotal;
}

echo 'Total: '.$total;

On-screen output after submitting the form, adding 4 products "Prod Name 1" and 5 products "Prod Name 2":

Nome: Nome Prod 1
Preço: 10
Quantidade: 4
Subtotal: 40

Nome: Nome Prod 2
Preço: 22
Quantidade: 5
Subtotal: 110

Total: 150

Browser other questions tagged

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