JasonDavis
JasonDavis

Reputation: 48933

jQuery Data Attribute not getting values

jQuery Data Attribute not working on the most simplest demo possible...

$( document ).ready(function() {

  $("#font_selection").change(function(){
    var fontImgName = $(this).data('font-img');
    //var fontImgName = $("#font_selection").data('font-img');

    //var fontImgName = $(this).attr('data-font-img')
    //var fontImgName = $("#font_selection").attr('data-font-img')

    alert(fontImgName);

  });

});

I must be missing something, I have tried every combination I can think of with no success, please help!

JSFiddle Demo here http://jsfiddle.net/8fvo3kw0/1/

Upvotes: 0

Views: 106

Answers (4)

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

That is because you're referencing to the select element itself.

var fontImgName = $(this).find('option:selected').data('font-img');

This would find the option that is selected and then access the data attribute of it. What you're doing is, you're selecting the data atribute's value of the select. In your HTML select doesn't have a data- attribute at all.

Upvotes: 1

HaBo
HaBo

Reputation: 14297

http://jsfiddle.net/8fvo3kw0/3/

$( document ).ready(function() {

  $("#font_selection").change(function(){
    var fontImgName = $(this).find('option:selected').data('font-img');      
    alert(fontImgName);
  });

});

Upvotes: 2

Mritunjay
Mritunjay

Reputation: 25882

You are trying to get the data attribute of select & your select doesn't have data attribute.

I think you want data attribute for selected Item

Use bellow

var fontImgName = $(this).find(':selected').data('font-img');

DEMO

Upvotes: 1

j08691
j08691

Reputation: 207901

You need to look at the selected option element:

var fontImgName = $(this).find('option:selected').data('font-img');

jsFiddle example

Upvotes: 2

Related Questions