Count characters while typing

Asked

Viewed 8,294 times

4

I’m developing a sales website and it has a product Lettering and each letter costs R$10,00.

How to calculate the value of a phrase the customer wants to buy?

For example, if the customer wants to buy his name, Betinho. The amount would come out for R $ 70,00 real.

How I do this validation and accounting through an input?

  • Ola Betinho Silva, Just now I had time to see what you asked there in the other post

5 answers

11


When accounting for the length of the word the final value also counts the spaces.

Now no longer:

var espaco = 0;
$('#nome').focus();

$('#nome').keyup(function(e) {

  if (e.keyCode == 8 || e.keyCode == 46) {
    espaco = 0;
    $('#nome').val("");
  }

  var text = $('#nome').val();

  if (text[text.length - 1] != ' ') {
    $('.preco').text((text.length - espaco) * 10 + ',00');
  } else {
    espaco++;
  }

});
body {
  font-size: 1.5em;
}

input {
  border: 0;
  background-color: transparent;
  border-bottom: 1px solid;
  width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Digite a palavra ou frase: <br><input id="nome" type="text" />

<div class='total' style='margin-top: 2%;'>
  Preço do produto R$: <span class='preco'></span>
</div>

Just take the last position of the string and check if it is equal to a space. In case ' '

Every time there is a space it adds +1 to the variable espaço which shall be subtracted from the final value and multiplied by the value of each letter.

I also added a snippet that detects whether Backspace or delete were pressed. This way it is possible to reset the variable espaco and clear the value of the field so there are no errors in multiplication.

  • And for me to get the "10" from the database? How do

  • It depends on several factors! What language do you use to relate html to the database? php?

5

Just take the length of your string.

var str = "Betinho";
var n = str.length;
console.log(n);

5

You need to count the number of characters that have the name with the function length, but this function counts the number of characters with spaces.

So that spaces are not multiplied to the value, we can count them split(" ").length - 1 and then subtract them from the calculation.

You can do it this way:

function calcular(el) {
  const valor = document.getElementById('valor');
  const precoPorLetra = 10;
  const espacos = (el.value.split(" ").length - 1); //conta espacos
  const caracteres = el.value.length;
  valor.value = parseFloat( (caracteres - espacos) * precoPorLetra).toFixed(2); //formatado para duas casas decimais
}
Nome: <input onkeyup="calcular(this)" type="text" />
Valor: <input id="valor" type="text" readonly />

  • How do I do this without having to click calculate... will typing and appearing the result already

  • As it is above, using the onkeyup on the tag input of the name when the user has just typed the letter.

  • good... just one question... is adding tbm the blank

  • How do I get this value "10" from the database?

3

You can get the size of a string through its field length.

So if you already have the word and the price, i.e.:

let palavra = "Betinho";
let precoUnitario = 10;

So:

let valorPalavra = precoUnitario * palavra.length;

To get the input value, the easiest way is with jQuery:

let palavra = $(idDoInput).val();

Or without jQuery, if you have unnecessarily long code fetish:

let palavra = document.getElementById(idDoInput).value;
  • $(idDoInput).val(); If he does not have much knowledge in Jquery this section will induce him to error. The most correct would be to exemplify in the correct way $('#idDoInput').val();

2

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

$(document).ready(function() {
    $('.soLetras').keyup(function (el) {

      $(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) * 10).toFixed(2);
	    
      total=total.replace(".", ",");
	    
      $('.total').html("R$ " + (total).replace(/\B(?=(\d{3})+(?!\d))/g, ".")); 
	    
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="soLetras" name="nome" id="nome" size="10" placeholder="Somente Letras">
<span class="total"></span>

Browser other questions tagged

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