The space key also becomes a character? LENGHT

Asked

Viewed 301 times

2

The space key also becomes a character?

My problem is that even if in input #userChat there is only the space key it even so gives the alert(), and it ends up being a big problem..

Keys: Space and Line Break. I need that I can only give one alert if you’ve actually written something, Characters, Letters, numbers, symbols, all sorts.

$('.butSend').click(function() {
    var mensagem = $("#userChat").val();
    var n = mensagem.length;
    if(n > 0){ 
        alert(mensagem);
    } 
});

2 answers

4


Yes the space is a character "blank", ie a space. You can get around this type of problem by making a trim in string:

$('.butSend').click(function() {
    var mensagem = $("#userChat").val().trim();
    var n = mensagem.length;
    if(n > 0){ 
        alert(mensagem);
    } 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="userChat"> <button class="butSend">Enviar</button>

To function trim removes all whitespace from the beginning and end of string and if it is made only of (spaces), then it will be empty.

2

You can do the following:

if($("#userChat").val().replace(/ /g,'')!=""){
     alert(mensagem);
}

then I used replace to remove the blank characters

  • 1

    Thanks for the help. ;)

  • In that case I don’t think he would remove line breaks, correct?

Browser other questions tagged

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