bobbyrne01
bobbyrne01

Reputation: 6763

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

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

second dialog

Upvotes: 2

Views: 4171

Answers (1)

fhelwanger
fhelwanger

Reputation: 475

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.

Upvotes: 2

Related Questions