-1

I have a select option dropdown like:

 <select name="futsalSelect" id="futsalSelect" class="form-control">
     <option data-timezone="MST" value="1" selected="">Sample futsal One</option>
     <option data-timezone="EST" value="3">Sample futsal Three</option>
 </select>

Now, I want to retrive that data-timezone value whenever I change that select option.

So, I tried with:

 $("#futsalSelect").change(function() {
     futsal_id = $(this).val();

     timezone = $(this).attr("data-timezone");
     console.log(timezone);  //undefined

     $("#futsalTimezone").text(timezone);
 });

But, it is returning undefined.

Aayush Dahal
  • 856
  • 1
  • 17
  • 51

4 Answers4

0

It is returning undefined because this inside the function refers to the main #futsalSelect element and not the selected option. To get the desired value, do it like this:

 $("#futsalSelect").change(function() {

     timezone = this.options[this.selectedIndex].getAttribute("data-timezone");
     console.log(timezone);

     $("#futsalTimezone").text(timezone);
 });
Devashish
  • 1,260
  • 1
  • 10
  • 21
0

use the option:selected selector:

 $("#futsalSelect").change(function() {
     futsal_id = $("#futsalSelect option:selected" ).val();

     timezone = $("#futsalSelect option:selected" ).attr("data-timezone");
     console.log(timezone);  //undefined

     $("#futsalTimezone").text(timezone);
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="futsalSelect" id="futsalSelect" class="form-control">
     <option data-timezone="MST" value="1" selected="">Sample futsal One</option>
     <option data-timezone="EST" value="3">Sample futsal Three</option>
 </select>
Waldir Bolanos
  • 422
  • 3
  • 7
0

You want to read the data attribute of the option, not of select. This will do it:

$('#futsalSelect').change(function() {         
     futsal_id = $(this).val();

     timezone = $(this).find('option:selected').data('timezone');
     console.log(timezone);  //undefined

     $('#futsalTimezone').text(timezone);
 });
Nawed Khan
  • 4,393
  • 1
  • 10
  • 22
0

you're trying to get the value from select data-timezone. you must take it to option inside select.

hope it helps.

Ricardo CF
  • 79
  • 5