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 ) );
}
You can add a CSS class to all of your select HTML elements and then, use jQuery CSS selector to retrieve all of them
And you retrieve all your select with