Add a character dynamically with PHP or JavaScript

0

There is some function that PHP or JavaScript does that adds a character (in this case a number) when a field has only 8 digits. within input . because I have a form where there is the RG field, and the RG is composed of 9 digits plus there are some users that have one less digit and would like that when the user types the RG field with only 8 digits it saves in the bank with a digit the more that would be 0

Remembering that everything is working normal on my site, I would really like it when the user types the RG with one digit unless he saves it with that 0

Link to site

    
asked by anonymous 26.05.2017 / 15:41

3 answers

3

You have the function str_pad :

<?php
print str_pad('45', 10, "0", STR_PAD_LEFT);  // Gera "0000000045"
print str_pad('23', 10, "0", STR_PAD_BOTH);  // Gera "0000230000"
print str_pad('76', 10, "0");  // Gera "6700000000"
    
26.05.2017 / 15:47
3

As commented, the best would be to adapt to your system accept the original user's RG value, with 8 characters. But in fact it is possible to add a X character to the end indicating that it does not exist - the 0 character I do not know to state, if you find a trusted source that says it ok.

With JavaScript it's pretty quiet; you simply treat any field event or form, check the length of the given data and add the desired character. See the example below, where I treated the event submit of the form.

  

I used return false to block event propagation because it is not needed here. In your case, this snippet must be removed in order for the event to propagate correctly.

function valida() {
  let rg = document.getElementById("rg");
  let span = document.getElementById("alert");

  if (rg.value.length < 9) {
    rg.value = rg.value + "X";
    span.innerHTML = "Seu RG foi modificado com a inserção de um X ao final por questões de compatibilidade";
  }

  return false;
}
<form action="" onsubmit="return valida();">
  <label for="rg">
    RG:
    <input type="text" id="rg" name="rg">
    <div id="alert"></div>
  </label>
  <input type="submit" value="Enviar">
</form>
    
26.05.2017 / 16:41
0

I have an idea, try to use Javascript. Create a javascript file put the following code:

$('.input-name').focusout(function(){
  var valor = $(this).val();
  if(valor.length < 9) $(this).val('0' + valor);   
});

Then copy the name input-name and add a class with the input-name value where you want to see this effect.

Remember that this code will add the number zero as soon as the user removes the cursor from the field and if the value in the field is less than 9.

    
21.11.2018 / 16:50