If input has only blanks, do nothing

Asked

Viewed 7,541 times

3

I’m making an application of chat with Websocket.

I used contenteditable="true" in a <div/>, because I needed to put so to facilitate in other functions.

On the part of input that sends the message to other users I’m having a problem, when the user type only blank spaces and click send, the message is sent, but I want when he type only blank spaces do not send the message.

Could someone please help me to make this code in Javascript or with Jquery itself?

HTML

<div id="message" contenteditable="true">Digite sua mensagem</div>

jQuery

// ENVIA COM O ENTER
$('#message').on('keydown', function(e) {

    var mymessage = $('#message').text(); //get message text
    var myname = $('.myname').text(); //get user name
    var mensagem = 'mensagem='+mymessage;
    var to = $(this).attr('id');
    var code = e.which || e.keyCode;

    if (e.which == 13 && e.shiftKey == false) {
        if (code == 13) {
            if (mensagem != '') {
                //$(".mensagens-unitarias").animate({"scrollTop": $('.mensagens-unitarias')[0].scrollHeight}, "fast");
                $.ajax({
                    type: 'POST',
                    url : 'sys/teste.php',
                    data: 'nome='+myname+'&mensagem='+mymessage,
                    success: function(html){}
                });

                if (mymessage == "") { return false; }

                //prepare json data
                var msg = {
                    message: mymessage,
                    name: myname,
                    color : '<?php echo $colours[$user_colour]; ?>'
                };

                //convert and send data to server
                websocket.send(JSON.stringify(msg));        
            }
        }

        return false;   
    }
})
  • Can you put the code that does this check? or the code that sends this input?

  • I can. See the edited question.

  • If I’m not mistaken, it is only possible to validate with HTML5, using the attribute Pattern of a input. But since you’re doing this in a div, the way is to use JS.

2 answers

3


One solution is to check two things:

  • If the size of string is strictly equal to nothing making use of property .length:

    string.length === 0
    
  • If after removing blanks a string is empty, making use of the method trim():

    !string.trim()
    

Example

Example also available on Jsfiddle.

$(function() {

  var $target = $('#message');

  $target.on("keyup", function() {

    var value = $target.text();

    if (value.length === 0 || !value.trim())
      return false;

    // continuar...
    alert(value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="message" contenteditable="true">Digite sua mensagem</div>

In the example above, a browser alert will appear with the value entered if this value has something other than whitespace.
If you type 1 or more blanks, nothing will happen.

Note: In use the event keyup to fire the code after the typed key and not when we go to type a new one, getting greater coherence between what is written on the screen and what the code is using to work with.

1

Forehead to change

if(mensagem != ''){

for

if(!mensagem.match(/^(\s)+$/)){

This regular expression will test this text to ensure that at the beginning of the text (^) there is white space (\s) in the quantity of 1 or more (+) and that after that the text ends ($). And then I deny the match with ! at the beginning of this condition, that is to ensure that this if only gives true if there is no match.

I guess that solves your problem.

  • Didn’t work out :(

  • @Daviddamasceno changes 1 more thing: use the keyup instead of keydown. Example: https://jsfiddle.net/hLk37a3a/

  • thanks, your example uses match, thanks ;)

Browser other questions tagged

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