Description:
I have many dropdowns on my page that all call a "update price" function. This is so that when user selects an option, the price changes accordingly. There are many of these dropdowns and they all have similar names sizes-1, sizes-2, etc
Problem
I am finding myself copy/pasting extremely similar event binding code because I can't figure out how to bind it through some sort of loop.
Example:
Static
$( '.sizes-1' ).on('change', function() { sizes[0] = $(this).val(); p.update_pricing( slider_values, price_fields, sizes, ); });Attempt at a loop ( not working )
for( index = 0; index < number of divs; index++ ) { $( '.sizes-' + index ).on('change', function() { sizes[ index ] = $(this).val(); p.update_pricing( slider_values, price_fields, sizes, ); }); }
There are going to be many .sizes divs on this page and I don't want to copy/paste that static code 30+ times. I was wondering if anyone ran into a similar problem and knows a solution?
Thank you very much.
Edit: ( copy/pasted code )
for( index = 0; index < num_divs; index++ ) {
( function( context_index ) {
$( '.sizes-' + context_index ).on( 'change', function() {
sizes[ context_index ] = $(this).val();
p.update_pricing( slider_values, price_fields, sizes );
});
} ( index ) );
}
size-1,size-2is understandable. But why would you have 30+ dropdowns with different class as such? A single class assizeswould really have solved your problem..changewill not be the correct value as the value ofiwill be equal tonumber of divsat the time of executing the handler function.select?