How to check variable only with javascript spaces?

Asked

Viewed 171 times

1

I have a chat system, and the send button should not be enabled until the user type some letter.

In the example below the button is enabled when the user type something, but if he only type spaces the button is displayed.

$('#msg').on('keyup',function() {
var textarea_value = $("#msg").val();

if(textarea_value != '') {
    $('.button-enviar').attr('disabled' , false);
    $('.button-enviar').removeClass('disabled');
}else{
    $('.button-enviar').attr('disabled' , true);
    $('.button-enviar').addClass('disabled');
}
});

How to check if the variable textarea_value contains only spaces? So do not enable the button.

1 answer

1


Taking advantage of the code you have and using Trim(), serves to remove end/start spaces from a string:

$('#msg').on('keyup',function() {
    var textarea_value = $("#msg").val().trim();
    if(textarea_value != '') {
        $('.button-enviar').attr('disabled' , false);
        $('.button-enviar').removeClass('disabled');
    }
    else{
        $('.button-enviar').attr('disabled' , true);
        $('.button-enviar').addClass('disabled');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="msg"></textarea>
<button type="button" class="button-enviar" disabled>ENVIAR</button>

Browser other questions tagged

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