0

I'm trying to obtain the html code from user input using a div contenteditable. Don't worry about HTML code injection, that is taken care of.

Anyway, when i enter

bla1
bla2
bla3

the output, i believe, should be

bla1<br>bla2<br>bla3

However, what i am getting is

bla1<div>bla2</div><div>bla3</div>

Sometimes it even becomes

bla1<div>bla2</div><div>bla3<br></div>

What is this??? What am i doing wrong here?

Example of the code: http://jsfiddle.net/ohhjjevf/3/

Aesreal
  • 131
  • 1
  • 12
  • 2
    The `contenteditable` input is indeed storing each new line as a `div` so that is the expected behaviour – Rob Schmuecker Jan 17 '15 at 10:29
  • if i do not use the contenteditable, is there any way to create a user input that allows html? – Aesreal Jan 17 '15 at 10:31
  • i'll change my question, is there any way for the contenteditable to store each new line as a new paragraph? or a new breakline instead of a div? – Aesreal Jan 17 '15 at 10:34
  • I would just then change the `
    ` and `
    ` tags to `br` or whatever you want https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
    – Rob Schmuecker Jan 17 '15 at 10:37

1 Answers1

1

as u can see in this answer - Dealing with line Breaks on contentEditable DIV

$editables = $('[contenteditable=true]');

$editables.filter("p,span").on('keypress',function(e){
 if(e.keyCode==13){ //enter && shift

  e.preventDefault(); //Prevent default browser behavior
  if (window.getSelection) {
      var selection = window.getSelection(),
          range = selection.getRangeAt(0),
          br = document.createElement("br"),
          textNode = document.createTextNode("\u00a0"); //Passing " " directly will not end up being shown correctly
      range.deleteContents();//required or not?
      range.insertNode(br);
      range.collapse(false);
      range.insertNode(textNode);
      range.selectNodeContents(textNode);

      selection.removeAllRanges();
      selection.addRange(range);
      return false;
  }

   }
});

will do.

Community
  • 1
  • 1
lakshya_arora
  • 791
  • 5
  • 18