jquery: Replace onclick event

javascript, jquery, jquery-ui

Solution

To remove an inline attribute using jQuery:

$('#tableA').find('#expand_' + row_id).removeAttr('onclick');

Does just that, yet, for IE < 9, you should use:

.prop('onclick', null);

As explained in the docs. I do wonder, however, why you're using `find` with an ID selector. I believe I'm right in saying `find` returns an array of jQ objects. Not a single DOM object. Perhaps:

$('#expand_' + row_id).prop('onclick', null);

is a better fit. To replace the `onclick` attribute with another one, you shouldn't need 2 `prop` calls, by the way:

$('#expand_' + row_id).prop('onclick', 'expandAndShow('+row_id+')');

basically removes the original `onclick` handler, by setting another handler. All in all, this kind of thing is best done using delegation:

$('#tableA').on('click', '*[id^=expand_]', function()
{
    alert($(this).attr('id').replace('expand_',''));
});

This code handles all click events, on all child elements of the `#tableA` element, that have an id, beginning with `expand_`. I then proceed to alert that id, without the `expand_` substring.

Problem

I have the following code: ``` $('#tableA').find("#expand_" + row_id).prop("onclick", null); $('#tableA').find("#expand_" + row_id).prop("onclick", 'expandAndShow('+row_id+')'); $('#tableA').find("#expand_" + row_id).removeClass('icon-plus-sign'); $('#tableA').find("#expand_" + row_id).addClass('icon-ok-sign'); ``` I wanted to replace previously linked `onlick` method with new one. It is not working. However, `removeClass` and `addClass` is working well. Am I missing anything?

Original source