0

I am working on the below code. Why am I not able to get the selected option's data attribute?

$('#type-picker').on('change', function (e) {
  var filter =  $(this).data("filter");
  console.log(filter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker" id="type-picker" data-width="100%" >
  <option data-filter="na" >Select From The List</option>
  <option data-filter="*">Display ALl</option>
  <option data-filter=".type1">Relish</option>
  <option data-filter=".type2">Relish</option>
  <option data-filter=".type3">Relish</option>
</select>
halfer
  • 19,824
  • 17
  • 99
  • 186
user1760110
  • 2,256
  • 5
  • 29
  • 37
  • In that context, `this` represents the ` – Alex K Jan 26 '17 at 18:55
  • Possible duplicate of [jQuery Get Selected Option From Dropdown](http://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) – demonofthemist Jan 26 '17 at 18:56

3 Answers3

3

$(this) will return the select itself, which has no data-filter, you need to get the selected option to obtain its filter attribute

$('#type-picker').on('change', function (e) {
  var filter =  $(this).find('option:selected').data("filter");
  console.log(filter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker" id="type-picker" data-width="100%" >
  <option data-filter="na" >Select From The List</option>
  <option data-filter="*">Display ALl</option>
  <option data-filter=".type1">Relish</option>
  <option data-filter=".type2">Relish</option>
  <option data-filter=".type3">Relish</option>
</select>
KAD
  • 10,972
  • 4
  • 31
  • 73
1

You are getting the data attribute of the select, not the option. Use $("#type-picker option:selected").

$('#type-picker').on('change', function (e) {
  var filter =  $("#type-picker option:selected").data("filter");
  console.log(filter);
});

Working Example: https://jsfiddle.net/mspinks/zdng9s5o/2/

Matt Spinks
  • 6,380
  • 3
  • 28
  • 47
0

You need to get the selected <option> inside the <select>. this keyword references the <select>

Here's how you can do it without jQuery

$('#type-picker').on('change', function (e) {
  var filter = this.children[this.selectedIndex].dataset.filter
  
  // this would also work
  //var filter = this.selectedOptions[0].dataset.filter
  
  console.log(filter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selectpicker" id="type-picker" data-width="100%" >
  <option data-filter="na" >Select From The List</option>
  <option data-filter="*">Display ALl</option>
  <option data-filter=".type1">Relish</option>
  <option data-filter=".type2">Relish</option>
  <option data-filter=".type3">Relish</option>
</select>
Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52