For example, I have the following input and datalist. After select option "a" from dropdown list, how to trigger a function?
The current way is only working after the focus is removed from input. What I want is, right after click the option, then it will trigger another function,Like trigger the javascript function?
I tried "onchange" and "onclick", it has to remove the focus. I want the action being triggered after option is selected.
<input id="endpointsInput_1" name="endpointsname_1" list="endpointsname_1" class="form-control" type="text" style="display:inline-block;width:100%;" onclick="getJsonRequest(1);"/>
<datalist id="endpointsname_1">
<option value="a">a</option>
<option value="b">b</option>
<option value="folders/delete">folders/delete</option>
<option value="c">c</option>
</datalist>
my script is as below.
<script type="text/javascript">
function getJsonRequest(i){
$("input[name=endpointsname_"+i+"]").change(function () {
alert($(this).val());}
Try this mate
document.getElementById('endpointsInput_1').addEventListener('input', function () {
console.log('changed');
});
I found a nice way to trigger a function exclusively on choosing an option from a datalist and not affecting manual input – using a keyup
event, and it works flawlessly on both desktop and mobile devices. When a datalist option is chosen, the event listener sees it as pressing a key without a keyCode
– the event object simply lacks the keyCode
property (I noticed it accidentally, checking keyup events with console.log). Below is a runnable example of code to blur an input and temporarily change its background color right after selecting a datalist option:
function blurInputOnDatalistChoice(e) { if (!e.keyCode) { // OR: if (e.keyCode === undefined) e.target.blur(); e.target.setAttribute('style', 'background-color:yellow'); setTimeout(() => e.target.removeAttribute('style'), 1500); } }
<h1>Demo</h1> <input onkeyup="blurInputOnDatalistChoice(event)" list="cars"></input> <datalist id="cars"> <option value="Audi"> <option value="BMW"> <option value="Volkswagen"> </datalist>
UPD: Datalist choices can also be detected the following way: the event that is generated in this case is just an instance of Event
, but NOT of KeyboardEvent
, as in case of pressing real keys. So, the alternative check is: if (!(e instanceof KeyboardEvent)) { }
.
Also, there is a possibility to listen for this purpose not to keyup
events, but to input
events: in this case choices from dataList will also trigger "unusual" events that are not instances of InputEvent
and also, unlike typical input events, lack the inputType
property.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.