Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: Replace onclick event

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?

like image 297
nebula Avatar asked Nov 18 '13 11:11

nebula


2 Answers

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.

like image 165
Elias Van Ootegem Avatar answered Sep 28 '22 04:09

Elias Van Ootegem


This should work

$('#tableA').find("#expand_" + row_id).unbind('click');
$('#tableA').find("#expand_" + row_id).on('click',expandAndShow(row_id));
like image 38
Mordalthunder Avatar answered Sep 28 '22 06:09

Mordalthunder