Place a value plus the variable in an input with javascript

1

Good what I want to do is that depending on the value that enters the input I put a V- or E-, but does not add when it is E-, or if there is already a V- does not change it. I attach the code.

 function evaluarContenido(cadenaIngresada){
      var evaluarCadena = cadenaIngresada.split("");
      var cadena=parseInt(evaluarCadena);
        if (cadena < 80000000) {
          if(evaluarCadena[0] != 'V'){
            $("#DNI").val("V-"+cadenaIngresada);
          }
        }else{
          if(evaluarCadena[0] != 'E'){
            $("#DNI").val("E-"+cadenaIngresada);
          }
        }
    }
.form-control {

  display: block;

  padding: 0.5rem 0.75rem;

  font-size: 1rem;

  line-height: 1.25em;

  color: #acaaa6;

  background-color: #fff;

  background-image: none;

  background-clip: padding-box;

  border: 1px solid rgba(0, 0, 0, 0.15);

  border-radius: 0; }
 .form-control-label {

  padding-top: 0.625rem; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="form-control-label">
                              Dni
                          </label>
<input class="form-control" name="DNI" id="DNI" value="" onchange="evaluarContenido(this.value)" maxlength="10" required="" type="text">
    
asked by rosibel vicent 28.03.2018 в 17:52
source

1 answer

4

I have not understood correctly what would be the meaning of doing split of your chain.

I propose this solution, which may be convenient for you. I explain what it consists of:

  • Whatever the value of input , you remove all the letters, keeping only the numbers by regex and stored in the variable valor . It is important to have a numerical data only for the evaluation that follows and for the future update of the input itself.
  • You have a ternary operator to evaluate valor , assigning V- or E- to variable letra as the case may be.
  • Finally, you combine letra and valor to update the content of input .

In this way the code is independent and you put the letter only at the end.

document.getElementById("DNI").onchange = function() {
  var valor = this.value.replace(/\D/g, "");
  var letra = (valor < 80000000) ? "V-": "E-";
  this.value = letra + valor;
}
<label class="form-control-label">
Dni
</label>
<input class="form-control" name="DNI" id="DNI" value="" maxlength="10" required="" type="text">

As an additional data, I have removed the function that listens to the onChange of the HTML element. I think it's a better practice, the more independent the HTML is, the better, in that way, if there's any change (for example, for some reason you want to call the function in another way and that function is used in inputs of different documents, only you change only once, in the Javascript, not in the HTML, however, you can do it as you had it, if you prefer.

    
answered by 28.03.2018 / 18:37
source