2
$('#selectSurvey').append('<option value="1" data-img="/path/image.png">'+ Option1 +'</option>');

$('#selectSurvey').on('change',function(e){
    $('#image-here').attr('src',this.data('img')); //wrong
});

How do I get the data in Option1 inside the dropdown on change?

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
clintgh
  • 2,039
  • 3
  • 28
  • 44

2 Answers2

3

Try to grab the selected option from the select element then retrieve the data,

$('#selectSurvey').on('change',function(e){
  $('#image-here').attr('src',$(this).find('option:selected').data('img')); 
});

Since the data-img has been set with the option element not with the select.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

You can try this:-

$('#selectSurvey').on('change',function(e){
   var img = $(this).find('option:selected').attr('data-img');
   $('#image-here').attr('src',img); 
});

or use .data() (if your jQuery version is newer ie >= 1.4.3)

$('#selectSurvey').on('change',function(e){
   var img = $(this).find('option:selected').data('img');
   $('#image-here').attr('src',img); 
});
DWX
  • 2,282
  • 1
  • 14
  • 15