donk
donk

Reputation: 1570

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.

Upvotes: 5

Views: 7774

Answers (5)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

You can escape the data before writing it to an attribute. Try out this fiddle

 $('#3h').attr('src', escape(url));

then

unescape($('#3h').attr('src'))

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179046

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.

Upvotes: 3

user113716
user113716

Reputation: 322492

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

Upvotes: 2

alexl
alexl

Reputation: 6851

For me it's working:

http://jsfiddle.net/y249K/

Upvotes: 1

Colin O&#39;Dell
Colin O&#39;Dell

Reputation: 8647

You could avoid using jQuery for this and use native JavaScript/DOM functions instead:

document.getElementById('3h').src = url;

Upvotes: -1

Related Questions