5

I'm having hard time in to getting the data attribute set to select option on bootstrap selectpicker .

I tried:

$('.selectpicker').on('changed.bs.select', function (e) {
    var selected = e.target.value;
    console.log("value :  ", selected ); // gives selected value
    console.log("data attribute:  ", $(e.target).data("price")); 
});

data attribute always returns undefined

what wrong I'm doing here ?

Chenna
  • 2,383
  • 3
  • 20
  • 36
monda
  • 3,809
  • 15
  • 60
  • 84
  • Could be several things from `e.target` not being what you expect, `console.log(e.target)` to confirm, or the element doesn't have the attribute assigned, spelled or specified as you expect. Please post the actual markup of the relevant DOM in a [**Minimal, Complete, and Verifiable example**](https://stackoverflow.com/help/mcve) using the code snipped feature. – Nope Feb 23 '18 at 15:37
  • 1
    exactly wich line return undefined ? Please, make a fiddle that reproduces the error. – lmarqs Feb 23 '18 at 15:37

4 Answers4

14

This works.

$('.selectpicker').on("changed.bs.select", function() {
    var dataTypeAttribute = $('option:selected', this).attr("data-type");
});
Pranay Majmundar
  • 803
  • 7
  • 15
2

Just specify id to select

$("#selectidhere").on("change", function () {
  var dataname = $("option[value=" + $(this).val() + "]", this).attr('data-name');
  alert(dataname);
});

Fiddle Link

Chenna
  • 2,383
  • 3
  • 20
  • 36
0
$('.selectpicker').on('changed.bs.select', function (e) {
var selected = e.target.value;
console.log("value :  "+selected ); // gives selected value
console.log("data attribute:  "+$(e.target).attr("data-price"));}); 
  • 2
    It would help to call out what you are providing here, it looks like your only change is "data" to "data-price", as the change from commas to string concat isn't going to change the logs. So would explain why your answers solves the question. – Cooper Buckingham Apr 24 '18 at 20:53
0
$(".selectpicker").on("changed.bs.select", 
    function(e, clickedIndex, isSelected, oldValue) {
        var arrayOfSelected = $('.selectpicker').eq(0).val();
        console.log(arrayOfSelected);
 });

It looks weird but it works perfectly so I don't care.