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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With