Rohit Pujar Rohit Pujar - 5 months ago 111
Javascript Question

Get selected value in autocomplete dropdown

I'm using awesomplete plugin to get an autocomplete dropdown. I'm able to get the dropdown working, however I find no straightforward way in accessing the value selected!

Here's the jsfiddle: https://jsfiddle.net/8y8xpqfk/1/

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Auto complete</title>
<link rel="stylesheet" href="css/awesomplete.css"/>
<script src="js/awesomplete.js" async></script>
</head>

<body>
<table>
<tr>
<td>
<input class="awesomplete" list="mylist" onchange="callMe()"/>
<datalist id="mylist">
<option>Ada</option>
<option>Java</option>
<option>JavaScript</option>
<option>Brainfuck</option>
<option>LOLCODE</option>
<option>Node.js</option>
<option>Ruby on Rails</option>
</datalist>
</td>
</table>

<script>
var callMe = function () {
alert("Something selected..");
}
</script>
</body>
</html>


The function never gets called,
onchange
is not triggered!

Answer

Mine is working. In order to obtain the selected value you have to pass the event object to the callMe function as argument. Then you could fetch the selected value.

function callMe(event) {
        alert("Something selected.."+event.target.value);
}
<body>
<table>
    <tr>
        <td>
            <input class="awesomplete" list="mylist" onchange="callMe(event)"/>
            <datalist id="mylist">
                <option>Ada</option>
                <option>Java</option>
                <option>JavaScript</option>
                <option>Brainfuck</option>
                <option>LOLCODE</option>
                <option>Node.js</option>
                <option>Ruby on Rails</option>
            </datalist>
        </td>
</table>
</body>

Comments