Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's attr() escaping ampersands

So i'm trying to set an image src attribute dynamically via javascript like so:

var url = 'query.php?m=traffic&q=getgraph&id='+pipeId+'&start=-3h';
console.log(url);
$('#3h').attr('src',url);

The problem is, it shows up like so query.php?m=traffic&q=getgraph&id=1&start=-3h in the console, the the actual set src for the #3h image element is query.php?m=traffic&q=getgraph&id=1&start=-3h

And then, of course, it doesn't work. How do I avoid jQuery's attr() methods' character escaping? Any other suggestions on how should I achieve my goal are very welcome as well.

like image 742
donk Avatar asked Feb 18 '11 17:02

donk


3 Answers

If it doesn't work, it's not due to the ampersands being escaped. As an attribute in an HTML element, all XML entities need to be escaped:

--+-------
< | &lt;
> | &gt;
" | &quot;
& | &amp;

As an example, if I had index.php?foo=bar&buzz=baz, and I wanted to have an a element target that page, I would need to set the anchor like so:

<a href="index.php?foo=bar&amp;buzz=baz

The href would get decoded as: index.php?foo=bar&buzz=baz

I'll see if I can't find the relevant documentation for you.

like image 150
zzzzBov Avatar answered Nov 19 '22 16:11

zzzzBov


The only issue that I see in your code is that your ID attribute is starting with a number, which is invalid in HTML4.

$('#3h') // invalid for HTML4

You should change the ID on the element to begin with a letter, like h3

$('#h3') // valid ID for HTML4
like image 23
user113716 Avatar answered Nov 19 '22 14:11

user113716


For me it's working:

http://jsfiddle.net/y249K/

like image 1
alexl Avatar answered Nov 19 '22 16:11

alexl