I need to grab each select option value in a dropdown and use them to generate an image attribute for each option. For example, if the value of the option is First Image the data-img-src value will be the path to the image folder/first-image.png
The below code works fine but it generates the data-img-src for the first option only. What I need is to return the data-img-src for each option in the dropdown. How can I do this?
jQuery(document).ready(function($){
$(".selector option").attr('data-img-src', function() {
var file = this.value + '.png';
var img = file.toLowerCase().replace(/ /g, '-');
var path = 'path to folder';
return path + img
});
});
Thanks in advance and have a good day.
You can use each() to iterate and update attribute of all options.
$(".selector option").each(function(){
$(this).attr('data-img-src', function() {
var file = this.value + '.png';
var img = file.toLowerCase().replace(/ /g, '-');
var path = 'path to folder';
return path+img
});
});
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