Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show an error on enter key press if textarea empty?

I have this chat which I am trying to make. Everything works ok so far but I want to show an error when I press enter if the textarea is empty. Can anyone tell me how I can do it? I've been trying many methods but nothing worked. Thank You.

$("#message").keypress(function(e) {
    var test = $("#Uname").val()
    var valmsg = $('#message').val();

    if (e.which == 13 && valmsg.trim()) {
        $("#chat").append("<div class='mesaj'>" + test+ ':' + valmsg + "  </div>");
        $('#message').val('');  
    }
});

Here is my code https://jsfiddle.net/azfwuzad/2/

like image 805
azazu testing Avatar asked Nov 24 '25 21:11

azazu testing


1 Answers

You can achieve this by checking that the value of the textarea is not empty when the return key is pressed. Try this:

$("#message").keypress(function(e) {
    var test = $("#Uname").val()
    var valmsg = $('#message').val();

    if (e.which == 13 && valmsg.trim() == "") {
        e.preventDefault();
        alert('Please type a message to send');
    } else if (e.which == 13) {
        $("#chat").append("<div class='mesaj'>" + test + ':' + valmsg + "</div>");
        $('#message').val('');
    }
});

Updated fiddle

The call to preventDefault() will stop the enter key press from adding a new line in an empty textarea.

like image 137
Rory McCrossan Avatar answered Nov 26 '25 11:11

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!