0

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/

4 Answers 4

2

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

$( document ).ready(function() {

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

});
Sign up to request clarification or add additional context in comments.

Comments

2

You need to look at the selected option element:

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

jsFiddle example

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.