0

I found on the internet a way to limit the number of characters; which is this:

jQuery

var myDiv = $('#your-div-id');
myDiv.text(myDiv.text().substring(0,300))

I'd like to limit the number of words. I have this code but I don't know how to use it to do what I want.

jQuery

var primo = document.getElementById('faketxt');
var wordLimit = 215;
var words = primo.textContent.replace(/(<([^>]+)>)/ig,"").split(/\s/);
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Niccolò Guidi
  • 195
  • 2
  • 14

2 Answers2

0

Based on this answer, the only thing you have to do to make it work with content editable divs is to use text() instead of val() :

var wordsLimit = 20;

$("#word_count").on('keyup', function() {
    var words = $(this).text().match(/\S+/g).length;
    if (words > wordsLimit) {
        // Split the string on first 200 words and rejoin on spaces
        var trimmed = $(this).text().split(/\s+/, wordsLimit).join(" ");
        // Add a space at the end to keep new typing making new words
        $(this).text(trimmed + " ");
    }
    else {
        $('#display_count').text(words);
        $('#word_left').text(wordsLimit-words);
    }
});

demo

Community
  • 1
  • 1
Brewal
  • 8,067
  • 2
  • 24
  • 37
  • bit trickier in browsers that create new block element for each new line. Other answer is for textarea which doesn't have child elements – charlietfl Feb 01 '17 at 17:10
  • I this case when I write more than 20 words, on the 21 it starts to delete the last one and writes the 21th a the beggining... doesn't work – Niccolò Guidi Feb 01 '17 at 22:00
  • This is another issue. Maybe you want to [keep the cursor at the end](http://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity/3866442#3866442) of your div ? Maybe you want to remove the "contenteditable" attribute ? But IMO this is answering your question – Brewal Feb 02 '17 at 10:49
0
<div contenteditable="true" id="text-div"></div>

var textDiv = document.getElementById("text-div");
if (textDiv.textContent.length < 1) {
    document.querySelector("#alert").textContent = "You must enter a text.";

    return;
  }
  console.log(textDiv.textContent.length);
ttfreeman
  • 5,076
  • 4
  • 26
  • 33