最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - selectpicker : Get the data attribute of selected option - Stack Overflow

programmeradmin2浏览0评论

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 ?

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 ?

Share Improve this question edited Jul 24, 2018 at 14:53 Chenna 2,6234 gold badges25 silver badges38 bronze badges asked Feb 23, 2018 at 15:33 mondamonda 3,91516 gold badges61 silver badges85 bronze badges 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. – Nope Commented Feb 23, 2018 at 15:37
  • 1 exactly wich line return undefined ? Please, make a fiddle that reproduces the error. – lmarqs Commented Feb 23, 2018 at 15:37
Add a comment  | 

4 Answers 4

Reset to default 16

This works.

$('.selectpicker').on("changed.bs.select", function() {
    var dataTypeAttribute = $('option:selected', this).attr("data-type");
});

Just specify id to select

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

Fiddle Link

$('.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"));}); 
$(".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.

发布评论

评论列表(0)

  1. 暂无评论