K. Peter
K. Peter

Reputation: 33

Javascript contenteditable error

This is my html code for displaying a editable textbox and is used as a "memo" element inside a webpage (inside a div tag).

contenteditable="true" name="choice1" class="textfield" max="872">Enter your Memo Here!

CSS:

    .textfield {
  max-width: 800px;
  width: 800px;
  border: 1px solid black;
  padding: 8px;
  margin: 20px;
  float:right;
  position: relative;
}

Javascript:

  var textfields = document.getElementsByClassName("textfield");
  for(i=0; i<textfields.length; i++){
      textfields[i].addEventListener("keypress", function(e) {
          if(this.innerHTML.length >= this.getAttribute("max")){
              e.preventDefault();
              return false;
          }
      }, false);
  }

However when I fill the editable div area with alot of spaces (" "), it takes less than the declared 872 characters to reach the maximum limit. Does anyone know why and have a solution? Thanks.

Upvotes: 2

Views: 313

Answers (1)

Rohith K P
Rohith K P

Reputation: 3551

Use textContent instead of innerHTML.

The textContent property sets or returns the textual content of the specified node, and all its descendants.

The innerHTML property sets or returns the HTML content (inner HTML) of an element.Which will include tags

In the below example I have set the max as 20

var textfields = document.getElementsByClassName("textfield");
for (i = 0; i < textfields.length; i++) {
  textfields[i].addEventListener("keypress", function(e) {
    if (this.textContent.length >= this.getAttribute("max")) {
      e.preventDefault();
      console.log('max reached') ;
      return false;
    }
  }, false);
}
<div contenteditable="true" name="choice1" class="textfield" max="20">Enter your Memo Here!</div>

Upvotes: 1

Related Questions