Horai Nuri
Horai Nuri

Reputation: 5578

How to avoid HTML text from breaking when inserted in input's value?

I would like to replace my hidden input's value with some html text and send it to the server as plain text. Here's how I did :

$('#div').append("<input type="hidden" value='<div><h1>Some text</h1><svg ...></svg></div>'");

The problem is that the code breaks and displays the value of the input as HTML tags into my template, which makes it unusable to the backend when sent.

Here's the jsfiddle: https://jsfiddle.net/Lindow/9p77afc3/2/, while inspecting you'll see that the svg got out of the input's value, that's what I'm trying to avoid.

How can I resolve this issue?

Upvotes: 0

Views: 81

Answers (2)

trincot
trincot

Reputation: 350300

Your input element is not hidden. Provide it with the type="hidden" attribute.

After you added that to your question you have a problem with not escaping quotes. Escape those inner double quotes with backslash, or use single quotes:

$('#div').append("<input type='hidden' value='<div><h1>Some text</h1><svg ...></svg></div>'");

After the next edit, which added the fiddle, it shows you have single quotes in the svg content, and that you do not quote the value property's value.

Do it like this:

$('.elements').append("<div>hey : <input hidden value=\"" + "<svg ... </svg>" + "\"</div>");
//                                                    ^^                         ^^

Corrected fiddle: https://jsfiddle.net/9p77afc3/4/

Upvotes: 2

Atul Kamani
Atul Kamani

Reputation: 105

Need to change single quotes instead of double quotes. Try below:

$('#div').append("<input type='hidden' value='<div><h1>Some text</h1><svg ...></svg></div>'");

Upvotes: 0

Related Questions