Souhaieb Besbes
Souhaieb Besbes

Reputation: 1504

JavaScript: how to set a value containing quotes inside a textbox

I have an MVC-project where I store data in a database and one of my views contains textboxes to edit this data.

Because of the specifics I can't create the textboxes directly via TextBoxFor(), EditorFor() etc. but have to affect the value with JavaScript, so what i do is write the needed value in the javascript code at page loading, and this code is later on triggered to affect the textbox value.

$("#textboxID").val("@HTML.Raw(Model.value)");

This workes fine until one of strings has got quotes in it.

When i input it directly like

$("#textboxID").val("@Model.value");

it will be HTML-encoded with the quotes written as > & quot; (without space of cource)

What i found out is that the only way to output quotes correctly is by escaping them with backslash \ however i can't seem to find a helper to do that. Is there a solution? Am i doing anything wrong?

For now, i found a workaround inspired by Filipe Borges suggestion

@Html.Raw(Html.Encode(Model.Libelle).Replace(""", "\\\""))

It's very ugly, but at least it solves the problem, I appreciate anyone suggesting a better solution.

Upvotes: 2

Views: 748

Answers (3)

Filipe Borges
Filipe Borges

Reputation: 2793

Solved using:

@Html.Raw(Html.Encode(Model.value).Replace(""", "\\\""))

First suggested replacing " by \" using @Model.value.replace(""", "\\\""), but it does not work because the value only contains " after the default html encoding is applied by mvc.

Edit: Final solution by Souhaieb Besbes. Edited mine to not keep it wrong.

Upvotes: 0

Souhaieb Besbes
Souhaieb Besbes

Reputation: 1504

For now, i found a workaround inspired by Filipe Borges suggestion

@Html.Raw(Html.Encode(Model.Libelle).Replace(""", "\\\""))

It's very ugly, but at least it solves the problem, I appreciate anyone suggesting a better solution.

Upvotes: 1

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

You can use single quote to show double quotes as following:

$("#textboxID").val('"'[email protected]+'"');

Upvotes: 0

Related Questions