Town
Town

Reputation: 14906

Get selector in event handler

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?

Upvotes: 5

Views: 3695

Answers (4)

Krishnaprasad MG
Krishnaprasad MG

Reputation: 529

You can always do:

for(var i in arr){
  $(arr[i]).bind('click', {'selector': arr[i]}, function(event){
    console.log(event.data.selector);
  });
}

Upvotes: 1

AlexC
AlexC

Reputation: 9661

$('div').click(function() {
    alert($(this)[0].nodeName);
});

Upvotes: 0

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

This guys seems to have done it. How do I get a jQuery selector's expression as text? - see Pim Jager's answer

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816364

$(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.

Upvotes: 5

Related Questions