Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change each option value javascript/jQuery

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.

like image 939
draison Avatar asked Mar 13 '26 20:03

draison


1 Answers

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
    });
});
like image 134
Adil Avatar answered Mar 16 '26 08:03

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!