Reputation: 896
I am trying to unbind this event:
$(document).on('change', $('select[name=url]'), function() {}) ;
When I unbind this event inside the change event using this, it works:
$(this).off();
But when I use this, it does not work:
$('select[name=url]').off();
Secondly, I'd like to unbind the event outside of the change event.
Upvotes: 0
Views: 594
Reputation: 1162
To remove specific delegated event handlers, you must provide a selector argument where the selector string must exactly match the one passed to .on() when the event handler was attached.
This way you dont have to use $(this).off() from inside the onchnage callback. Also, using namespaces for events makes sure you don't unbind any undesired events
Try this.
//here the namespace name is set to 'selection'
$(document).on('change.selection', 'select[name=url]', function() {
alert("Change event triggered");
})
$("button").click(function() {
$(document).off('change.selection', 'select[name=url]')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="url">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button>Unbind</button>
Upvotes: 3
Reputation: 166
It is beacuse the event on('change')
is bindded to the document not to the element ('select[name=url]')
.
If you want to set the event change for every element select, the best option is to set a common class and bind the change event to the class.
If you do that, you can unbind the event inside and outside to the change event
Upvotes: 0