views:

63

answers:

2

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 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>

Any idea how to render this on the page so the postback message contains the correct value?

+7  A: 

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

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

You can see this working in a jsFiddle example here. Alternatively, you can delimit the attribute value with single quotes:

<option value='"asd'>test</option>
Andy E
OP's fourth option, ", is also a valid way to escape quotes. There's a benefit to using numeric html entities over named entities, in that named entities do not cover all characters, while numeric entities do. The full HTML4 list is at http://www.w3.org/TR/html4/sgml/entities.html .
atk
@atk: yes, `"` maps to the same character as `"`, but there's no benefit of using the numeric option here because `"` is a defined named entity. `"` is also easier to remember.
Andy E
@Andy E: I agree. In this particular case, it's easier to use ". I intended only to point out the general case.
atk
Thanks, my problem in this case turned out to be unrelated...
Chris
A: 

If you're generating the options using ASP or ASP.NET use the HTMLEncode method:

<option value="<%=Server.HTMLEncode(data)%>">test</option>

This will automatically convert double quotes and more special characters.

Shadow Wizard