Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  142] [ 3]  / answers: 1 / hits: 165482  / 15 Years ago, tue, may 5, 2009, 12:00:00

I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:

  • Using jQuery attr(onclick, js) doesn't work with both Firefox and IE6/7.

  • Using setAttribute(onclick, js) works with Firefox and IE8, but not IE6/7.

  • Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().

Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.

<script type=text/javascript
<script type=text/javascript>
var js = alert('B'); return false;;
// Set with JQuery: doesn't work
$(a).attr(onclick, js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById(anchor).setAttribute(onclick, js);
<a href= id=anchor onclick=alert('A'); return false;>Click</a>

More From » jquery


You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

var js = alert('B:' +; return false;;
// create a function from the js string
var newclick = new Function(js);

// clears onclick then sets click using jQuery
$(#anchor).attr('onclick', '').click(newclick);

That should cancel the onClick function - and keep your javascript from a string as well.

The best thing to do would be to remove the onclick= from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

You also said:

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

No - it won't, but onclick = eval((function(){+js+})); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors

[#99591] Thursday, April 30, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 150
Total Questions: 103
Total Answers: 113

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago