JavaScript + PHP character counting function

-1

I have this function that counts the characters and shows me the value:

function calcular(el) {
  var valor = document.getElementById('valor');
  var precoPorLetra = 10;
  var espacos = (el.value.split(" ").length - 1); //conta espacos
  var caracteres = el.value.length;
  valor.value = parseFloat( (caracteres - espacos) * precoPorLetra).toFixed(2); //formatado para duas casas decimais
}

I need to get the "precoPorLetra" of the database (PHP + MYSQL). I need to show the "value" also in a <span>

<span id="valor"></span>

But nothing appears

Nome: <input onkeyup="calcular(this)" type="text" />
Valor: <input id="valor" type="text" readonly />
    
asked by anonymous 14.08.2017 / 21:29

1 answer

2

With Javascript to display in a span also just insert this line

document.getElementById('valor_span').innerHTML = "R$ "+preco_total;

Changing the value of id in tag span to valor_span since id=valor has already been assigned to input

function calcular(el) {
  var valor = document.getElementById('valor');
  var precoPorLetra = 10;
  var espacos = (el.value.split(" ").length - 1); //quantidade de espacos
  var caracteres = el.value.length;
  preco_total = valor.value = parseFloat( (caracteres - espacos) * precoPorLetra).toFixed(2); //duas casas decimais
  
  document.getElementById('valor_span').innerHTML = "R$ "+preco_total;
  
}
Nome: <input onkeyup="calcular(this)" type="text" />
Valor: <input id="valor" type="text" readonly />

<span id="valor_span"></span>

With jquery

  • Accepts only letters, including accents (not to inflate prices with commas, dots, special characters and so on: D)
  • Thousands separator . (dot) and decimal , (comma)
  • Spaces are accepted but are not counted

$(document).ready(function() {
    $('.soLetras').keyup(function (el) {
    var precoPorLetra = 10;

      $(this).val($(this).val().replace(/[^a-zA-Zà-úÀ-Ú ]/g,''));
      var nome = document.getElementById('nome');
  
      var espacos = (nome.value.split(" ").length - 1);

      var letras = nome.value.length;		    
      var total = parseFloat((letras-espacos) * precoPorLetra).toFixed(2);
	    
      total=total.replace(".", ",");
      
      total=total.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
	    
      $('.valor').html("R$ " + total); 
      
      valor.value = total;

	    
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Nome:<inputtype="text" class="soLetras" name="nome" id="nome">
Valor: <input id="valor" type="text" readonly />
<span class="valor"></span>
  

To also accept numbers replace this line

$(this).val($(this).val().replace(/[^a-zA-Zà-úÀ-Ú ]/g,''));

by this line

$(this).val($(this).val().replace(/[^a-zA-Zà-úÀ-Ú0-9 ]/g,''));

PHP

The value of precoPorLetra from the bank can be assigned in the script as follows:

var precoPorLetra = <?php echo $nomeVariavel ?>;
    
15.08.2017 / 01:35