Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check that contenteditable div is empty or not

I have a content-editable div that works as Textarea.

<div id="divThatYouCanWriteStuffIn" contenteditable="true" class="ibox-content col-lg-12">
</div>

Now I want check whether this div is empty or not, for validations.

What I used is as below.

 if ($('#divThatYouCanWriteStuffIn')[0].innerText == "") {
        alert("Please update your wall, then post.")
        return false;
  }

But it's not working if user just clicked enter in div. Same way I have used

 if ($('#divThatYouCanWriteStuffIn')[0].innerText.length <= 1) {
        alert("Please update your wall, then post.")
        return false;
    }

$('#divThatYouCanWriteStuffIn').html()

But it also has break tags inside div, as it takes blank as break

So, is there any way to check that editable div is not empty and has some proper text?

like image 725
Bharat Avatar asked May 06 '16 09:05

Bharat


People also ask

What is Contenteditable div?

Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.

What is false about Contenteditable attribute?

contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.

How do I turn off Contenteditable div?

Just set contentEditable="false" . See this answer.


2 Answers

You can use the text() method to get the relevant content(content without html tags)

  if ($('#divThatYouCanWriteStuffIn').text().trim().length == 0) {
    alert("empty");
  }

.trim() function removes all the white spaces and newline characters from the beginning and end of the content.

Fiddle

like image 188
Anoop Joshi P Avatar answered Sep 21 '22 19:09

Anoop Joshi P


Incase your contenteditable div contains html. I used this method below

divHtml = $('div#divThatYouCanWriteStuffIn').html();
checkEmpty = divHtml.replace(' ', '').replace('<br>', '');
if(checkEmpty.length == 0){
    alert('empty');
}

Replace all space with nothing and all line breaks <br> with nothing also

like image 26
KANAYO AUGUSTIN UG Avatar answered Sep 23 '22 19:09

KANAYO AUGUSTIN UG