I am trying to determine if a textarea is empty if a user deletes what is already pre-populated in the textarea using jQuery.
Anyway to do this?
This is what
if (!$("#myTextArea").val()) {
// textarea is empty
}
You can also use $.trim to make sure the element doesn't contain only white-space:
if (!$.trim($("#myTextArea").val())) {
// textarea is empty or contains only white-space
}
This will check for empty textarea as well as will not allow only Spaces in textarea coz that looks empty too.
var txt_msg = $("textarea").val();
if (txt_msg.replace(/^\s+|\s+$/g, "").length == 0 || txt_msg=="") {
return false;
}
$.each(["input[type=text][value=]", "textarea[value=]"], function (index, element) {
//only empty input and textarea will come here
});
To find out if the textarea is empty we have a look at the textarea text content and if there is one sinlge character to be found it is not empty.
Try:
if ($(#textareaid).get(0).textContent.length == 0){
// action
}
//or
if (document.getElmentById(textareaid).textContent.length == 0){
// action
}
$(#textareaid)
gets us the textarea jQuery object.
$(#textareaid).get(0)
gets us the dom node.
We could also use document.getElmentById(textareaid)
without the use of jQuery.
.textContent
gets us the textContent of that dom element.
With .length
we can see if there are any characters present.
So the textarea is empty in case that there are no characters inside.
You just need to get the value of the texbox and see if it has anything in it:
if (!$(`#textareaid`).val().length)
{
//do stuff
}
if(!$('element').val()) {
// code
}