Does the space key also become a character? LENGHT

2

The space key also becomes a character?

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

Keys: Space and Line Break. I need that I can only give alert if you have actually written something, Characters, Letters, numbers, symbols, just things.

$('.butSend').click(function() {
    var mensagem = $("#userChat").val();
    var n = mensagem.length;
    if(n > 0){ 
        alert(mensagem);
    } 
});
    
asked by anonymous 03.08.2015 / 16:34

2 answers

4

Yes the space is a "blank" character, that is, a space. You can work around this type of problem by doing a trim in string : p>

$('.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><inputtype="text" id="userChat"> <button class="butSend">Enviar</button>

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

    
03.08.2015 / 16:44
2

You can do the following:

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

In this case I used replace to remove the blank characters

    
03.08.2015 / 16:41