Total Input radio PHP

Asked

Viewed 61 times

0

I have this site and I need to implement a sum with input[type=radio].

That’s the page where I do the sums

This is the Javascript code that makes the sums.

<script>
        function formatCurrency(num) { // função original - sem modificação
          num = num.toString().replace(/\$|\,/g, '');
          if (isNaN(num)) num = "0";
          cents = Math.floor((num * 100 + 0.5) % 100);
          num = Math.floor((num * 100 + 0.5) / 100).toString();
          if (cents < 10) cents = "0" + cents;
          for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
          return ("" + num + "." + cents);
        }

        var form = document.forms[0];
        var inputs = form.querySelectorAll('input[type=radio]');
        // iterar todos os inputs
        for (var i = 0; i < inputs.length; i++) {
          // vincular função ao evento "change"
          inputs[i].addEventListener('change', function() {
            var soma = 0;
            for (var j = 0; j < inputs.length; j++) {
              if (inputs[j].checked) {
                // interpreta como float, usando parseFloat ao invés de eval
                soma += parseFloat(inputs[j].value);
              }
            }
            form.hiddentotal.value = soma; // atribui valor ao campo oculto
            form.total.value = formatCurrency(soma) // exibe valor formatado
          }, false);
        }
                        </script>

But nothing appears... it does not generate the result...

In this other link it works perfectly... should it be something in the code?

Link that works

  • That ain’t java, that’s right javascript. They are very different languages.

  • @Sorry Moltres :D

2 answers

2


Modifications to be made

  • The form <form action="/teste.php" name="formulario" id="formulario" method="post">
  • Put values value="10.00" and no names value="Com moldura" in all the input type radio in the frameless place value="0"
  • In the script change to var form = document.getElementById('formulario');

Below an executable example

function formatCurrency(num) { // função original - sem modificação
   num = num.toString().replace(/\$|\,/g, '');
   if (isNaN(num)) num = "0";
	cents = Math.floor((num * 100 + 0.5) % 100);
	num = Math.floor((num * 100 + 0.5) / 100).toString();
	if (cents < 10) cents = "0" + cents;
	  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
	    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
	    return ("" + num + "." + cents);
}
							
	var form = document.getElementById('formulario');
	var inputs = form.querySelectorAll('input[type=radio]');
	// iterar todos os inputs
	for (var i = 0; i < inputs.length; i++) {
	  // vincular função ao evento "change"
	  inputs[i].addEventListener('change', function() {
	    var soma = 0;
	    for (var j = 0; j < inputs.length; j++) {
		if (inputs[j].checked) {
		  // interpreta como float, usando parseFloat ao invés de eval
		  soma += parseFloat(inputs[j].value);
		}
	    }
	    form.hiddentotal.value = soma; // atribui valor ao campo oculto
	    form.total.value = formatCurrency(soma) // exibe valor formatado
          }, false);
        }

function show2nomes() { 
 document.getElementById('show2nomes').style.display='';
 document.getElementById('show1nome').style.display='none';
}

function show1nome() {
 document.getElementById('show1nome').style.display='';
 document.getElementById('show2nomes').style.display='none';
}

function escondeMolduraDetalhe() {
 document.getElementById('escondeMolduraDetalhe').style.display='none';
 document.getElementById('showMolduraDetalhe').style.display='none';
}

function showMoldura() {
 document.getElementById('showMoldura').style.display='';
}
function showPessoas() {
 document.getElementById('showPessoas').style.display='';
}
function showMaterial() {
 document.getElementById('showMaterial').style.display='';
}
function showFormato() {
 document.getElementById('showFormato').style.display='';
}
function showMolduraDetalhe() {
 document.getElementById('showMolduraDetalhe').style.display='';
}
<div class="page_content_offset" id="anchor">
<div class="container">				
<div class="row clearfix">						
<!--<form name="formulario" id="dadosPlacas" action="/modulos/loja/funLoja.php?op=add&produto_id=" method="post" enctype="multipart/form-data">-->
<form action="/teste.php" name="formulario" id="formulario" method="post">												
						
<section class="col-lg-6 col-md-6 col-sm-6 m_xs_bottom_30 pull-right">								
<h4 class="text-center m_bottom_25"><strong>Dados para fabricação</strong></h4>
<h4 class="text-center m_bottom_25"><strong>TAMANHO DA MOLDURA</strong></h4>
<div class="row texto-radio">
																		
<div class="col-md-3">											
<input type="radio" value="1.00" name="tamanho" id="tamanho1" onClick="showPessoas();">
<label for="tamanho1">06x08 cm</label>										
</div>
<div class="col-md-3">											
<input type="radio" value="2.00" name="tamanho" id="tamanho2" onClick="showPessoas();">
<label for="tamanho2">08x10 cm</label>
</div>
<div class="col-md-3">											
<input type="radio" value="3.00" name="tamanho" id="tamanho3" onClick="showPessoas();">
<label for="tamanho3">09x12 cm</label>
</div>
<div class="col-md-3">											
<input type="radio" value="4.00" name="tamanho" id="tamanho4" onClick="showPessoas();">
<label for="tamanho4">11x14 cm</label>										
</div>																	        <div class="col-md-3">											
<input type="radio" value="5.00" name="tamanho" id="tamanho5" onClick="showPessoas();">
<label for="tamanho5">13x18 cm</label>
</div>
<div class="col-md-3">											
<input type="radio" value="6.00" name="tamanho" id="tamanho6" onClick="showPessoas();">
<label for="tamanho6">18x24 cm</label>
</div>
																			
</div>
								
<!-- FOTOS -->
<div id="showPessoas" style="display: none">
<hr>
<div class="row texto-radio">
<div class="col-lg-4 col-md-4 col-sm-12">
<h4 class="pt-20"><strong>PESSOAS NA FOTO</strong></h4>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">
<input type="radio"  value="10.00" name="imagem" id="campo-radio1" onChange="show1nome();" onClick="(show1nome(), showFormato());">
<label for="campo-radio1">1 PESSOA</label>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">
<input type="radio"  value="20.00" name="imagem" id="campo-radio2" onChange="show2nomes();" onClick="(show2nomes(), showFormato());">
<label for="campo-radio2">2 PESSOAS</label>
</div>
</div>
</div>
<!-- CAMADAS NOME INPUT -->
<div class="row">
<div id="show1nome" style="display: none;">
<input type="file" class="full_width">
</div>
</div>
<div class="row">
<div id="show2nomes" style="display: none;">
<div class="f_left half_column">
<label for="cf_name" class="required d_inline_b m_bottom_5">1ª foto</label>
<input type="file" id="cf_name" name="cf_name" class="full_width r_corners">
</div>
<div class="f_left half_column">
<label for="cf_name" class="required d_inline_b m_bottom_5">2ª foto</label>
<input type="file" id="cf_name" name="cf_name" class="full_width r_corners">
</div>
</div>
</div>									
<!--. CAMADAS NOME INPUT -->
<!--. FOTOS -->
									
<!-- FORMATO -->
<div id="showFormato" style="display: none">
<hr>
<div class="row texto-radio">
<div class="col-lg-4 col-md-4 col-sm-12">
<h4 class="pt-20"><strong>FORMATO</strong></h4>
</div>
										
<div class="col-lg-4 col-md-4 col-sm-12">										
<input type="radio" value="4.00" name="formato" id="formato1" onClick="showMoldura();">
<label for="formato1">Oval</label>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">										
<input type="radio" value="6.00" name="formato" id="formato2" onClick="showMoldura();">
<label for="formato2">Retangular</label>
</div>																				
										
</div>
</div>
									
<!-- MOLDURA -->
<div id="showMoldura" style="display: none">
<hr>									
<div class="row texto-radio">									
<div class="col-lg-4 col-md-4 col-sm-12">
<h4 class="pt-20"><strong>MOLDURA</strong></h4>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">
<input type="radio" value="0" name="moldura" id="sem-moldura" onClick="(escondeMolduraDetalhe(), showMaterial());">
<label for="sem-moldura">SEM MOLDURA</label>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">
<input type="radio"  value="10.00" name="moldura" id="com-moldura" onChange="showMolduraDetalhe();" onClick="showMolduraDetalhe();">
<label for="com-moldura">COM MOLDURA</label>
</div>									
</div>									
</div>
									  									   									
<!-- CAMADAS NOME INPUT -->
<div id="showMolduraDetalhe" style="display: none;">
<div class="row texto-radio">
<div class="col-lg-4 col-md-4 col-sm-12">&nbsp;</div>		
<div class="col-lg-4 col-md-4 col-sm-12">
<input type="radio"  value="6.00" name="modelo_moldura" id="modelo_moldura1" onClick="showMaterial();">
<label for="modelo_moldura1">Floral</label>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">
<input type="radio"  value="10.00" name="modelo_moldura" id="modelo_moldura2" onClick="showMaterial();">
<label for="modelo_moldura2">Lisa</label>
</div>
																					 									
</div>
</div>
									
<div class="row">
<div id="escondeMolduraDetalhe" style="display: none;">											
</div>
</div>									
<!--. CAMADAS NOME INPUT -->
  									
<!-- MATERIAL -->
<div id="showMaterial" style="display: none">
<hr>																		
<div class="row  texto-radio">
<div class="col-lg-4 col-md-4 col-sm-12">
<h4 class="pt-20"><strong>MATERIAL</strong></h4>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">											
<input type="radio" value="5.00" name="material" id="material1" onClick="(showPessoas(), showMaterial());">
<label for="material1">Alumínio</label>
</div>
<div class="col-lg-4 col-md-4 col-sm-12">											
<input type="radio" value="10.00" name="material" id="material2" onClick="(showPessoas(), showMaterial());">
<label for="material2">Bronze</label>
</div>
</div>
</div>
<div>
<span>Valor Total:</span>
<input name="total" type="text" readonly disabled>
<input type="hidden" name="hiddentotal" value="0">
</div>
								  									
</section>							
</form>

example on an online page

  • Leo... once again my thanks now was rs :D I need another help... as I sum letters. Ex. Each letter is worth 10 real if I write Carla total 50 real... how do I do it?

  • @Betinhosilva in what context? PHP?

  • In another context.. in this link: http://placasparatumulo.com.br/categoria/3/letras-handwritten. - I’m going to ask another question so as not to disturb this one

  • is at this link https://answall.com/questions/226255/somar-letras-com-pre%C3%A7o-javascript

0

the problem of not working on this page is that Document.Forms[0]; return the first form of the page, in this case, the survey form. assign an id to the form you want to do the math, or put (since you have jquery):

var form = $(".page_content_offset form").first();

AMENDMENT: How jquery is loaded after this function (the <script src="/js/jquery-2.1.1.min.js"></script> is after), should put inside a doc ready to run only after loading everything. And since you have a form id, you can "search" for the id var form = $("#formulario");. That’s how it goes:

var form = document.forms[0];

<script>
        function formatCurrency(num) { // função original - sem modificação
          num = num.toString().replace(/\$|\,/g, '');
          if (isNaN(num)) num = "0";
          cents = Math.floor((num * 100 + 0.5) % 100);
          num = Math.floor((num * 100 + 0.5) / 100).toString();
          if (cents < 10) cents = "0" + cents;
          for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
          return ("" + num + "." + cents);
        }

    $( document ).ready( function () {
        var form = $("#formulario");
        var inputs = form.querySelectorAll('input[type=radio]');
        // iterar todos os inputs
        for (var i = 0; i < inputs.length; i++) {
          // vincular função ao evento "change"
          inputs[i].addEventListener('change', function() {
            var soma = 0;
            for (var j = 0; j < inputs.length; j++) {
              if (inputs[j].checked) {
                // interpreta como float, usando parseFloat ao invés de eval
                soma += parseFloat(inputs[j].value);
              }
            }
            form.hiddentotal.value = soma; // atribui valor ao campo oculto
            form.total.value = formatCurrency(soma) // exibe valor formatado
          }, false);
        }
  });
  </script>
  • I did as you instructed and nothing happened...

  • some suggestion?

  • if I do $( Document ).ready( Function () { var form = $("#formulario"). first(); } is wrong?

  • Since jquery is loaded after this function, you should even put everything within $( Document ).ready( Function () { ... }. I will update the answer.

Browser other questions tagged

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