Error Javascript Code When Using Keyup Event

Asked

Viewed 61 times

-1

I am using the keyup event to call a javascript function, and thus format the typed content within my input. However, it does not work properly as expected.

The idea is: put only the first letter in upper case, the rest it forces lower case. When it is word with only 2 characters, it always sets in lowercase.

The problem is that by pressing the space key inside the input or pressing the Backspace key inside the empty input, the function returns the word "Undefined" inside the field.

I am also doubtful if I should use any other more suitable event for this case.

Follow jsfiddle link so you can check.

$(document).ready(function() {


  function ajustaNome(text) {
    var loweredText = text.toLowerCase();
    var words = loweredText.split(" ");
    for (var a = 0; a < words.length; a++) {
      var w = words[a];

      var firstLetter = w[0];

      if (w.length > 2) {
        w = firstLetter.toUpperCase() + w.slice(1);
      } else {
        w = firstLetter + w.slice(1);
      }

      words[a] = w;
    }
    return words.join(" ");
  }
  $('#campo_nome_empresa').keyup(function() {

    var campo_nome_empresa = $("#campo_nome_empresa").val();
    var nomenome = ajustaNome(campo_nome_empresa);


    $("#campo_nome_empresa").val(nomenome);


  });



});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  Codigo para colocar apenas a primeira letra maiscula. Se a palavra tiver apenas duas letras, ela deverá continuar minúscula.<br><br> Exemplo, se a pessoa digitar:<br> - luis sanches de oliveira<br> - LUIS SANCHES DE LIVEIRA<br><br> o resultado será:<br>  - <b>Luis Sanches de Oliveira</b>
</p>

<input name="campo_nome_empresa" type="text" class="form-control input-md" id="campo_nome_empresa" maxlength="150">

https://jsfiddle.net/4Ls16bu3/

  • "works correctly as expected", what was expected? What was the unexpected behavior you saw? Here he left the first letter uppercase when I typed 3 letters. That’s not what he was supposed to do?

  • I’ll edit my question .

1 answer

1


Assuming you have the value "luis ", when dividing into the blank, loweredText.split(" "), you will get the array ["luis", ""]. The undefined appears because within the loop you access the 0 position of the word, but "" does not have position 0.

In this case, just validate the size of the string obtained before doing anything:

$(document).ready(function() {


  function ajustaNome(text) {
    var loweredText = text.toLowerCase();
    var words = loweredText.split(" ");
    
    for (var a = 0; a < words.length; a++) {
      var w = words[a];
      
      // Se for uma string vazia ignora
      if (w.length === 0) continue;

      var firstLetter = w[0];

      if (w.length > 2) {
        w = firstLetter.toUpperCase() + w.slice(1);
      } else {
        w = firstLetter + w.slice(1);
      }

      words[a] = w;
    }
    return words.join(" ");
  }
  $('#campo_nome_empresa').keyup(function() {

    var campo_nome_empresa = $("#campo_nome_empresa").val();
    var nomenome = ajustaNome(campo_nome_empresa);


    $("#campo_nome_empresa").val(nomenome);


  });



});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  Codigo para colocar apenas a primeira letra maiscula. Se a palavra tiver apenas duas letras, ela deverá continuar minúscula.<br><br> Exemplo, se a pessoa digitar:<br> - luis sanches de oliveira<br> - LUIS SANCHES DE LIVEIRA<br><br> o resultado será:<br>  - <b>Luis Sanches de Oliveira</b>
</p>

<input name="campo_nome_empresa" type="text" class="form-control input-md" id="campo_nome_empresa" maxlength="150">

  • Hi Anderson! Thank you so much for the support and explanation. = D Worked perfectly.

Browser other questions tagged

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