selectpicker : Get the data attribute of selected option
Asked Answered
D

4

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 ?

Dieterich answered 23/2, 2018 at 15:33 Comment(2)
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 using the code snipped feature.Misdirection
exactly wich line return undefined ? Please, make a fiddle that reproduces the error.Underhanded
C
16

This works.

$('.selectpicker').on("changed.bs.select", function() {
    var dataTypeAttribute = $('option:selected', this).attr("data-type");
});
Cown answered 6/3, 2019 at 18:11 Comment(0)
S
2

Just specify id to select

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

Fiddle Link

Solent answered 24/7, 2018 at 14:9 Comment(0)
I
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"));}); 
Intercalary answered 24/4, 2018 at 17:19 Comment(1)
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.Hike
E
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.

Ephialtes answered 3/8, 2022 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.