-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">
"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?
– Woss
I’ll edit my question .
– Luis