Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selector in event handler

Tags:

jquery

I answered this question with this jQuery code:

$('input[type="checkbox"][name$="chkSelect"]').click(function() {
  $('input[type="checkbox"][name$="chkSelect"]').not(this).prop("checked", false);
});

... and it got me thinking: there must be a way to avoid duplicating the selector in the event handler.

I tried $(this).selector but that just returns an empty string. Here's a demo.

Is there a way to get the selector text in the event handler?

like image 236
Town Avatar asked Jun 24 '11 15:06

Town


2 Answers

$(this).selector does not work because you create a new jQuery object and pass a DOM element, not a selector.

If you only want to avoid repeating the selector, you can cache the elements beforehand (which is better anyway):

var $elements = $('input[type="checkbox"][name$="chkSelect"]');
$elements.click(function() {
    $elements.not(this).prop("checked", false);
});

But I don't think there is a way to get the selector inside the event handler. The only reference you have to the selected elements is the corresponding DOM element (through this). But you cannot "reverse engineer" the selector from that.

like image 101
Felix Kling Avatar answered Oct 07 '22 00:10

Felix Kling


You can always do:

for(var i in arr){
  $(arr[i]).bind('click', {'selector': arr[i]}, function(event){
    console.log(event.data.selector);
  });
}
like image 31
Krishnaprasad MG Avatar answered Oct 07 '22 00:10

Krishnaprasad MG