Rossitten
Rossitten

Reputation: 1166

How to check if a line inside contenteditable div is empty

How can I change this code so it detects whether a line inside contenteditable div is empty of has text?

$('#area').on("keyup change", function() {
    if( this.value.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
     && this.value.substr(this.selectionStart).match(/^(?:\s+|$)/)) {
        console.log("empty");
    } else {
        console.log("has stuff");
    }
});

works the way it should with textarea. I tried to replace VALUE with innerHTML - alas! with no luck.

http://jsfiddle.net/5uZjV/1/

UPDATE: what I am looking for is to find out if A SEPARATE LINE is empty. For example - try to add several lines and then delete any line using backspace. Deleting one symbol by one - when there are no more symbols on the line - script should return "empty". Example:

  1. line number one text // on "Del"/"Backspace" keyup returns "has stuff"
  2. // on "Del"/"Backspace" keyup returns "empty"
  3. line number three text // on "Del"/"Backspace" keyup returns "has stuff"

Upvotes: 0

Views: 549

Answers (2)

Suchit kumar
Suchit kumar

Reputation: 11859

with your code(added mouseover to get div status on mouseover) using innerHTML:

$('#area').on("keyup change mouseover", function() {
   if( this.innerHTML.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
 && this.innerHTML.substr(this.selectionStart).match(/^(?:\s+|$)/)){
    console.log("empty");
    } else {
    console.log("has stuff");
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div name="" id="area" style="width:100px;height:100px;border:1px solid black;" contenteditable=true></div>

With mouseover and get the data using innerHTML.

$('#area').mouseover( function() {
    if( this.innerHTML.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
     && this.innerHTML.substr(this.selectionStart).match(/^(?:\s+|$)/)) {
        console.log("empty");
    } else {
        console.log("has stuff");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div name="" id="area" style="width:100px;height:100px;border:1px solid black;" contenteditable=true></div>

Upvotes: 2

Ekim
Ekim

Reputation: 1105

You need to change the .value to .textContent.

$('#area').on("keyup change", function() {
   if( this.textContent.substr(0,this.selectionStart).match(/(?:^|\s+)$/)
 && this.textContent.substr(this.selectionStart).match(/^(?:\s+|$)/)){
    console.log("empty");
    } else {
    console.log("has stuff");
   }
});

and change the textarea to div if I understood you correctly.

<div name="" id="area" cols="30" rows="10" contenteditable=true></div>

Upvotes: 2

Related Questions