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 ?>;