Reputation: 9701
I have this little function :
$('.chrnumberpickerDiv select').change(function(){
var sel = $(this),
value = sel.closest('.chrnumberpickerDiv').find('.chrnumberpickerDivText');
value.text(sel.find(':selected').text());
}).one('change');
My problem is that I also need to trigger it on DOM load. I have tried .trigger('change')
instead of .one('change')
but it seems like it goes in a loop and never stops refreshing my page. So what could I be doing to trigger the event on DOM but without causing any damages to other events or whatever makes the function go in a loop ?
Upvotes: 0
Views: 165
Reputation: 46647
If I understood your question, you need to trigger a function when the select changes, as well as programmatically trigger it when the page loads to populate an initial value:
// define the handler
var changeHandler = function() {
var sel = $(this),
value = sel.closest('.chrnumberpickerDiv').find('.chrnumberpickerDivText');
value.text(sel.find(':selected').text());
};
// bind the handler
$('.chrnumberpickerDiv select').change(changeHandler);
$(document).ready(function () {
// execute the handler on page load
// use proxy to change what "this" means in the handler
// (jQuery does this for you when you bind a handler through jQuery)
$.proxy(changeHandler, $('.chrnumberpickerDiv select')[0]));
});
Upvotes: 1
Reputation: 1952
Try this, instead of your code
$(document).ready(function() {
$('.chrnumberpickerDiv select').change(function(){
var sel = $(this),
value = sel.closest('.chrnumberpickerDiv').find('.chrnumberpickerDivText');
value.text(sel.find(':selected').text());
}).one('change');
});
you have be careful not to assign multiple change functions. Otherwise all of them are called when the change event happens.
Upvotes: 0