Omar Gonzales
Omar Gonzales

Reputation: 4008

Why getting the value of datalist is not working?

Ho can I alert the value of the selected option of my datalist, values are: 1,2 or 3.

According to this other question, it should work like it is.

Codepen:

https://codepen.io/ogonzales/pen/gOMZarJ

HTML:

<div class="__range __range-step __range-step-popup">
                <input value="1" type="range" max="3" min="1" step="1" list="performance_options">
                <datalist id="performance_options">
                    <option value="1">1080p</option>
                    <option value="2">1440p (2k)</option>
                    <option value="3">4K</option>
                </datalist>
                <output class="__range-output-square"></output>
            </div>

JS:

alert($('#performance_options').attr('value'));

alerts "undefined", expected 1,2 or 3.

Upvotes: 0

Views: 209

Answers (1)

A. Meshu
A. Meshu

Reputation: 4148

If you want to alert any option you should select it...

This will alert the first one:

alert($('#performance_options option').attr('value'));

And this will alert all of them:

$('#performance_options option').each(function(index, value) {
  alert(`option${index}: ${this.value}`);
});

Since you want to alert the one that the user select you should listen to the input change value and alert the same option text:

$('[type="range"]').on('change', function() {
  let val = this.value;
  alert($("#performance_options option[value=" + val + "]").prop("selected", true).text());
});

Upvotes: 1

Related Questions