R. StackUser
R. StackUser

Reputation: 2065

how to do an action on both keyup and item selection on text input with datalist?

I'm sure there's a very simple answer, I have a text input box bound to a datalist. I can use jquery to fire an event for every key typed ("change keyup"), but I also want to fire an event when an item is selected from the datalist dropdown.

With the code below, I'd need to click the item then press a key to activate.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
    <datalist id="mydata"><option value="select1" /><option value="select2" /></datalist>
    <input type="text" list="mydata" />
    </div>
    <script>
    $("#div1").delegate(":input", "change keyup", function (e) {
    console.log('fired');
    });
    </script>

What event would trigger after an item selection as well? Onclick doesn't seem like a good option, as it will fire on any click.

Upvotes: 1

Views: 561

Answers (1)

qiAlex
qiAlex

Reputation: 4346

Best event in your case is to use the input event, instead of the change or keyup events.

$("#div1").delegate(":input", "input", function (e) {
console.log('fired');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="div1">
<datalist id="mydata"><option value="select1" /><option value="select2" /></datalist>
<input type="text" list="mydata" />
</div>

Upvotes: 1

Related Questions