Modify ↓
Ticket #4281 (closed bug: wontfix)
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@… |
| Blocking: | Blocked by: |
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
Change History
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.
Note: See
TracTickets for help on using
tickets.

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?