user6731422 user6731422 - 1 month ago 5
HTML Question

Trying to prevent posting empty value in a textarea using javascript

I have a simple application that submits that from a textarea on entering the enter command of the keyboard. I am trying to prevent the user from submit empty data to the form using javascript, here is my attempt but my challenge is that it is submitting to pressing enter keyboard

document.getElementById('new-input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length > 0) { // enter key press && $(this).val().length > 0
e.preventDefault();
send();
}
});


here is the send method

function send() {
var message = document.getElementById('new-input').value.trim(),
xhr = new XMLHttpRequest();
// alert('first message>>>>> '+message);

xhr.onload = function (response) {
if (xhr.status === 200) {
document.getElementById('new-input').value = '';

} else {
alert('Request failed. Returned status of ' + xhr.status);
location.href = '/';
}
};
xhr.send(encodeURI('message=' + message));

}


Please how can I prevent the user from submitting empty value. using either angularjs or javascript

Answer

You can to use $.trim to check to white-space:

if ( code == 13 && $.trim($(this).val()) )

Will be returns true if not empty.