I want to get the selected text in searchable dropdown using javascript function. My expected output is my selected text. But in below code, always return the value as undefined. There's an another problem with this dropdown. When I click one time on the dropdown, it doesn't show the dropdown items. Always, I have to double click to see the dropdown items. My main issue is how to get the seleted text using js function. Hope your help.
document.querySelector('#get-value').addEventListener('click', ()=> {
var elmValue = document.querySelector('#suggestions').value;
document.querySelector('#result').innerHTML = elmValue;
})
<datalist id="suggestions">
<option>First Option</option>
<option>Second Option</option>
</datalist>
<input class="form-control" autoComplete="on" list="suggestions" id="agentName"/>
<button id="get-value">
Get Value
</button>
<p>
Selected Value: <span id="result"></span>
</p>
Thank you.
I found a solution for this issue. I included name attribute to the input field.
<input class="form-control" autoComplete="on" list="suggestions" id="agentName" name="agentName"/>
Then, using the line of code below, I was able to get the selected text.
var selectedValue = $('[name="agentName"]').val();