jqueryjquery-select2jquery-select2-4

How to get custom data-attribute of select2 selected values


I have found similar question with solution here: Get custom data-attribute in select2 with <select>

I have placed custom data attribute with each option.

<option value="pen" data-price="2.5">Pen</option>

When I applied the accepted solution of that question,

var price = $(this).select2().find(':selected').data('price');

I get "Cannot read property 'current' of null".

Here is my fiddle demo


Solution

  • Your price variable is iterable. You have to iterate all selected options.

    Try this:

        $('.select-multiple').change(function () {
          var price = $(this).find(':selected');
    
          $.each(price, function(){
              console.log('Price: ', $(this).data("price"));
          });
        });
    

    JSFiddle