Reputation: 1570
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
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
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:
--+-------
< | <
> | >
" | "
& | &
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&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
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
Reputation: 8647
You could avoid using jQuery for this and use native JavaScript/DOM functions instead:
document.getElementById('3h').src = url;
Upvotes: -1