How do I properly escape quotes inside HTML attributes?

Chris picture Chris · Oct 25, 2010 · Viewed 246.7k times · Source

I have a drop down on a web page which is breaking when the value string contains a quote.

The value is "asd, but in the DOM it always appears as an empty string.

I have tried every way I know to escape the string properly, but to no avail.

<option value=""asd">test</option>
<option value="\"asd">test</option>
<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>

How do I render this on the page so the postback message contains the correct value?

Answer

Andy E picture Andy E · Oct 25, 2010

&quot; is the correct way, the third of your tests:

<option value="&quot;asd">test</option>

You can see this working below, or on jsFiddle.

alert($("option")[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="&quot;asd">Test</option>
</select>

Alternatively, you can delimit the attribute value with single quotes:

<option value='"asd'>test</option>