Skip to main content

Bug Tracker

Side navigation

#4281 closed bug (wontfix)

Opened March 02, 2009 04:36PM UTC

Closed October 02, 2010 11:15PM UTC

Last modified March 14, 2012 03:22PM UTC

Can't overwrite onclick attr

Reported by: gelform Owned by:
Priority: minor Milestone: 1.4
Component: attributes Version: 1.3.2
Keywords: onclick attribute attr Cc: corey@gelform.com
Blocked by: Blocking:
Description

On an element, I can add an attribute of onclick:

$('#myLink').attr('onclick', "alert('test');")

But then I cannot rewrite/reset it:

$('#myLink').attr('onclick', "alert('test2');") doesn't work

$('#myLink').attr('onclick', "") doesn't work

and if I remove it, I cannot then readd it:

$('#myLink').removeAttr('onclick') works

$('#myLink').attr('onclick', "alert('test3');") doesn't work

Attachments (0)
Change History (3)

Changed March 03, 2009 01:01AM UTC by dmethvin comment:1

There is some magic that the browsers do to convert the string onclick attribute into an onclick function property. When you set the onclick *attribute* to a string it also sets the onclick *property* to a function object that it creates from the string you gave it.

When you set the onclick attribute the second time, jQuery sees the existing onclick property and believes that it should set the property in preference to the attribute. In doing that it changes the function to a string.

However, you can still change the onclick handler by assigning a function directly to the property, rather than the attribute:

  $('#myLink')[0].onclick = function(){ alert("test2"); };

You can also clear the onclick the same way by assigning a null.

Is there a reason why you're avoiding the jQuery event support?

Changed June 26, 2010 03:46AM UTC by dmethvin comment:2

component: supportattributes
summary: Can't overwrite onclick attr or re-add it after removingCan't overwrite onclick attr

Changed October 02, 2010 11:15PM UTC by snover comment:3

resolution: → wontfix
status: newclosed

I don’t feel that jQuery should do anything to encourage bad practices like this. Feel free to reopen if there is any disagreement in that regard.