views:

13

answers:

1

I have a javascript function which takes a string as its parameter. This string is encoded (with %20 for spaces, %26 for ampersands, etc..).

function myFunction(theParam) {
       alert(theParam); // outputs &
}

// called by the following link
<a href="#" onclick='myFunction("%26")'>Do something</a>

How do I stop this behavior? I want myFunction to receive %26 as the parameter and not the ampersand......

+1  A: 

Your example alerts %26 as expected for me. (And then falls through to navigating to #. Remember to return false from a click handler to stop the link being followed.)

You would get an ampersand if you did it in a javascript: link:

<a href="javascript:myFunction('%26')">Do something</a>

as javascript: URLs are still URLs and undergo normal URL-escaping rules. Of course, you should never use a javascript: URL anyway.

Better, assign from JavaScript itself so you don't have to worry about HTML-escaping issues either:

<a href="#" id="somethingdoer">Do something</a>

document.getElementById('somethingdoer').onclick= function() {
    myFunction('%26');
    return false;
};
bobince
Good catch. In my actual complicated real-world version, it was using a javascript: URL. I've now changed it to href="#" and it works. Thanks!
David
aside: there's still some controversy over whether one should use `<a href="#">` either, since it's not really a link. Other approaches include a `<span>` (potentially with scripted keypresses and `tabindex` to make it respond to keyboard interaction), or a `<button>` styled not to look like a button (which is best for usability/accessibility, but requires a fair bit of cross-browser CSS faffing).
bobince