Prem ThAqqar
Prem ThAqqar

Reputation: 137

How to Get Text Of Selcted index in datalist tag

I want inner text of option tag with pure js

Here is my HTML

<input list="in" name="i_n" class="form-control" placeholder="Enter Item Name" required>

<datalist id="in" onChange="rate(this)">

    <option value='value'>Inner Text</option>

</datalist>

Here is my script

function rate(sel)
{
        var a=sel.options[sel.selectedIndex].text;
        alert(a);
}

And there is no message in Console.

Upvotes: 1

Views: 1797

Answers (4)

herrstrietzel
herrstrietzel

Reputation: 17293

You can also get the corresponding datalist textContent via attribute selector:

inputEl.addEventListener('change', (e) => {
  let datalistId = e.currentTarget.getAttribute('list');
  let datalistOption = document.querySelector(`#${datalistId} option[value="${e.currentTarget.value}"]`);
  
  currentSelection.textContent = datalistOption ? datalistOption.textContent : '';
})
label {
  display: block
}
<p>
  <label id="currentLabel">Current Selection: <span id="currentSelection"></span></label>
  <input id="inputEl" list="mydatalist" placeholder="Enter Item Name">
</p>

<datalist id="mydatalist" onChange="rate(this)">
    <option value='item1_value'>Item 1</option>
    <option value='item2_value'>Item 2</option>
    <option value='item3_value'>Item 3</option>
</datalist>

Upvotes: 0

PREM
PREM

Reputation: 114

You are Using Datalist Wrong Way!.. DataList is not select Tag Both are different.

Upvotes: 1

Arun AK
Arun AK

Reputation: 4370

You can use this function to get the value of datalist.

document.getElementById('int').addEventListener("change",function () {
   var g=this.value;
   alert(g);
});

Here is the working Link

Upvotes: 0

Abhishek Dey
Abhishek Dey

Reputation: 1639

$('#in option').each(function(index) {
    var a = $(this).text();

    alert(a);
});

OR

$("#in option:selected").text()

Upvotes: 0

Related Questions