2

http://jsfiddle.net/bobbyrne01/Lnq5mffs/

HTML ..

<input type="text" id="separator" value="Doesnt\nwork" />
<input type="button" id="button" value="submit" />

javascript ..

document.getElementById('button').onclick = function(){
    alert(document.getElementById('separator').value);
    alert("This\nworks");
};

Output ..

  • first dialog:

first dialog

  • second dialog:

second dialog

bobbyrne01
  • 6,295
  • 19
  • 80
  • 150
  • Use a textarea for multiline input. – user2182349 Jun 12 '15 at 15:46
  • try logging out the value returned by document.getElementById('separator').value in the console – PiX06 Jun 12 '15 at 15:46
  • @PiX06 this is whats logged: `"Doesnt\nwork"` – bobbyrne01 Jun 12 '15 at 15:48
  • Escaping only works on a predefined set of characters within an HTML attribute, so `\n` literally prints out `\n`. You could use ` ` as a newline character (or an actual line break in the HTML itself), but then `` doesn't allow for multilines. Use a ` – CodingIntrigue Jun 12 '15 at 15:49
  • 2
    It's interpreted as literate characters. If you do want to enter \n, you have to replace it in code with real carriage return e.g. http://jsfiddle.net/Lnq5mffs/1/ – Yuriy Galanter Jun 12 '15 at 15:52
  • 1
    http://stackoverflow.com/questions/358874/how-can-i-use-a-carriage-return-in-a-html-tooltip – yas Jun 12 '15 at 15:54

1 Answers1

2

It's right, "\n" means "new line" only when used in a string literal. You can't expect that an avarage user will enter "\n" in an input box expecting that it'll be interpreted as a new line. When the user enters "\n" in the input box, the value property is set to "\\n".

If you really need the input box content to be interpreted as a string literal, you can use replace, like in this fiddle: http://jsfiddle.net/Lnq5mffs/2/.

document.getElementById('button').onclick = function(){
    alert(document.getElementById('separator').value.replace('\\n', '\n'));
    alert("This\nworks");
};

Edit: If you want to provide your user a way to enter multi-line text, use textarea: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea.

fhelwanger
  • 465
  • 4
  • 9