Is there a way to trigger a JavaScript event specifically after selecting a datalist option? By that I don’t mean if any input has been entered, or even if an input identical to an option in the datalist has been typed in manually.
I only want it to trigger if you specifically CLICK the option from the datalist displayed.
I tried $('#search-data').click()
and $('#search-data options').click()
, but neither triggered.
$('#search-options').click(function(){
alert("test");
});
$('#search-options options').click(function(){
alert("test 2");
});
<datalist id="search-options">
<option>Test1</option>
<option>Test2</option>
</datalist>
<input id="search-bar" type="text" list="search-options" class="form-control" placeholder="Search" aria-label="Search">
<script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>
3
Answers
Listen for the
blur
event on the<input>
element when the<input>
loses focus, capture the entered value then check if it matches any of the<option>
s.The same solution can work with any other event, like the
input
event,change
event, etc. Choose the one that matches your expectations I guess.If you don’t need to check if any input has been entered, or if an input identical to an option in the datalist has been typed in manually, you can try this.
This solution uses the input event and checks the type of the event object. If the type is not InputEvent, then it means that the input event was caused by a datalist option selection, not by keyboard input, mouse input, or paste input. By using this approach, you can trigger a JavaScript event specifically after selecting a datalist option.
So the issues are:
I added a bunch of listeners to a datalist:
keyup, keydown, paste, input, change
and observed the following:Clicking on an item in the datalist triggers a keyup event with an empty (undefined) keycode, followed by whatever other events are related to the input changing, followed by a keydown event with an empty keycode.
Pasting will trigger a paste event, typing will trigger a key event that is non-undefined. So create a listener for all of the events, and then check whenever we see this pattern:
Log each heard event in an array, and then check the array for a valid chain.
Disclaimer
This seems to work, but its hacky, subject to breaking, and only tested in chrome