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>

2

3 Answers 3

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>

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

Comments

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/

Comments

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>

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.