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?
$(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.
You can always do:
for(var i in arr){
$(arr[i]).bind('click', {'selector': arr[i]}, function(event){
console.log(event.data.selector);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With