views:

62

answers:

4

I'm trying to set attribute value that contains a single quote:

var attr_value = "It's not working";
var html = "<label my_attr='" + attr_value + "'>Text</label>";
$('body').html(html);

However, I get the following result:

<label working="" not="" s="" my_attr="It">Text</label>

How could I fix this ?

Are double quotes allowed inside attribute values ?

+1  A: 
var attr_value = "It&#39;s not working"
Marco Mariani
+1  A: 

Use double-quotes as the attribute delimiter:

var html = "<label my_attr=\"" + attr_value + "\">Text</label>";
Marcelo Cantos
+1  A: 

You can use single quotes inside double quotes or double quotes inside single quotes. If you want to use single quotes inside single quotes or double quotes inside double quotes, you have to HTML encode them.

Valid markup:

<label attr="This 'works'!" />
<label attr='This "works" too' />
<label attr="This does NOT \"work\"" />
<label attr="And this is &quot;OK&quot;, too />
CodeTwice
The one with the backslashes doesn't work. That's a JavaScript escape, not HTML.
bobince
You are right, I edited my response and removed the escaping.
CodeTwice
+5  A: 

Yes, both quotes are allowed in attribute values, but you must HTML-escape the quote you're using as an attribute value delimiter, as well as other HTML-special characters like < and &:

function encodeHTML(s) {
    return s.split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;').split("'").join('&#39;');
}

var html= '<label my_attr="'+encodeHTML(attr_value)+'">Text</label>';

However, you are usually much better off not trying to hack a document together from HTML strings. You risk bugs and HTML-injection (leading to cross-site-scripting security holes) every time you forget to escape. Instead, use DOM-style methods like attr(), text() and the construction shortcut:

$('body').append(
    $('<label>', {my_attr: attr_value, text: 'Text'})
);
bobince
Thanks a lot for a detailed answer! Just for curiosity regarding the implementation of `encodeHTML`: It can be implemented using the `replace` function, right ? Is it less effective ?
Misha Moroshko
bobince
Thanks ! Could you give me a pointer to "construction shortcut" tutorial ?
Misha Moroshko
See eg http://www.milesj.me/blog/read/77/Element-Creation-In-JQuery-1.4
bobince
Thanks! You are great!!
Misha Moroshko