In javascript, newline character specified via input does not create a newline in alert

3.9k views Asked by At

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

1

There are 1 answers

0
fhelwanger On BEST ANSWER

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.