Skip to content Skip to sidebar Skip to footer

How To Avoid Removing Typed Text From Contenteditable

In Jquery

I'm using jQuery UI draggable component to add to content editable

. The expected output was, paragraph

should be editable and the draggable compone

Solution 1:

Sometimes the user-entered text is removed again, and the cause is in the function unChunkWords:

This function iterates only over elements (with class "w"), but it does not iterate over the plain text nodes that may occur in-between those elements. And in a content-editable element, the user can indeed type text in areas between elements. And so this loop in unChunkWords will never visit such text, omitting it in the array it returns.

You can force it to happen by putting the cursor at the end of a word, before a space, then press the right arrow key. Either this moves the cursor to the start of the next word, or it does not move visibly (it just moved out of the span it was in). Either way, your cursor is now in the text node that separates the two words. Type something and click somewhere else. ... the anomaly happens.

There are many ways to circumvent this. One of them is to use the jQuery contents() method, which also collects text nodes. Change the following code:

$(".w", tObj).each(function(i, el) {
  if ($(el).hasClass("b")) {
    words.push("[" + $(el).text().trim() + "]");
  } else {
    words.push($(el).text().trim());
  }
});

...to this:

$(tObj).contents().each(function (i, el) {
  if (el.nodeType !== 3 && !$(el).is(".w")) return; // Only regard ".w" or text nodesif ($(el).hasClass("b")) {
    words.push("[" + $(el).text().trim() + "]");
  } else {
    words.push($(el).text().trim());
  }
});

Now the text you enter will not be omitted from words, even when you type it in text nodes that are direct children of the content-editable element.

Adding spaces

Your code is adding spaces with .join(" ") without verifying that the text fragments are really separated by white space in the content of the p element. So, I would just grab all content, including spacing and just concatenate that. That way you will have the word separations exactly as they are in the p element.

So then your function would be:

functionunChunkWords(tObj) {
    var words = "";
    $(tObj).contents().each(function (i, el) {
      if ($(el).hasClass("b")) {
        words += "[" + $(el).text() + "]";
      } else {
        words += $(el).text();
      }
    });
    return words.replace(/\s+/g, " ").trim();
  }

Disclaimer: I have only looked at this particular problem, pointing out why you have this particular behaviour, and how to fix it. This does not mean that now your code will work correctly in all its intended functionality, which would go beyond the scope of the question.

Post a Comment for "How To Avoid Removing Typed Text From Contenteditable

In Jquery"