-1

I just tried to create a button with multi-line text value,

<input type="button" value="Carriage&#13;&#10;return&#13;&#10;separators" style="text-align:center;">

The above piece of code works, however when i try to set the value using jquery it is not working, the inputted value has been rendered as it is. How can we render the inputted text as same as, while we set the value through HTML.?

JS:

$('input').val('Carriage&#13;&#10;return');

NON WORKING DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130

4 Answers4

3

The string you give val isn't HTML, it's a JavaScript string. To use carriage returns and newlines, you use \r and \n:

$('input').val('Carriage\r\nreturn');

Updated Fiddle

In contrast (and a lot of people miss this, kudos to you on that), the text inside an attribute in HTML is HTML text, so you can (and sometimes must) use character entities there.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks for the timely response.. Any way i need to look into this kind of topics to sharpen my skills much better.. can you link me to the relevant articles. i really don't know the technical term for it. Thanks. – Rajaprabhu Aravindasamy Sep 08 '14 at 13:37
  • @RajaprabhuAravindasamy: np. I'm afraid I can't immediately think of relevant things to link to other than general JS resources. The key here is separation of concerns: The browser's HTML parser is what reads your attribute values, and it expects to see HTML text there, so you can use character entities there. But the text in JavaScript is JavaScript text, controlled by the rules for JS string literals, which use character escapes like the ones I gave. Sometimes, you give a JavaScript string to something that will then interpret it as HTML (like jQuery's `html` function), but usually not. – T.J. Crowder Sep 08 '14 at 13:41
  • 1
    Yeah i am clear now.. Thanks a bunch. Accept this soon. – Rajaprabhu Aravindasamy Sep 08 '14 at 13:43
  • Don't think that this is a chameleon question.. Our solution is not working in IE browsers.. Any ideas to fix it in ie browsers..? – Rajaprabhu Aravindasamy Sep 09 '14 at 09:39
  • 1
    @RajaprabhuAravindasamy: IE may not support line breaks in `input[type="button"]` elements. You can probably switch to using `button[type="button"]` elements instead (you can leave the `type` off if they're not in a `form`, it's just that in a `form` they're submit buttons if you don't put the `type` on). `button` elements are allowed to have rich content, so you could use `Carriage
    Return` as their `html`.
    – T.J. Crowder Sep 09 '14 at 11:44
1

Use \n for new line when placing new strings to inputs

jsfiddle: http://jsfiddle.net/nLf9deb0/

Tooschee
  • 681
  • 6
  • 11
1

Try this:

$('input').val('Carriage\r\nreturn');
Think Different
  • 2,815
  • 1
  • 12
  • 18
0

Try below code:

$('input').val('Carriage\r\nreturn');

Demo :-

http://jsfiddle.net/vjf4ctjg/6/

Neel
  • 11,625
  • 3
  • 43
  • 61