In Javascript, it is possible, through onchange
, oninput
and related, to detect if a certain input
is changed.
Example:
var qs = function (el) { return document.querySelector(el); }
qs("#input").addEventListener('input', function (e) {
console.log('evento "input" %s', e.target.value);
});
qs("#input").addEventListener('change', function (e) {
console.log('evento "change" %s', e.target.value);
});
<input type="text" id="input" />
Using the <datalist>
tag you can also suggest fills to input
. It is also possible to detect these changes in the input, since selecting an item from a datalist
fills the target input.
Example:
var qs = function (el) { return document.querySelector(el); }
qs("#input").addEventListener('input', function (e) {
console.log('evento "input" %s', e.target.value);
});
qs("#input").addEventListener('change', function (e) {
console.log('evento "change" %s', e.target.value);
});
<input type="text" id="input" list="datalist"/>
<datalist id="datalist">
<option>Bola</option>
<option>Peão</option>
<option>Pipa</option>
</datalist>
However, in my scenario, the following need arose: Instead of detecting changes in input
, I need to know specifically, through an event, when a option
of that datalist
is selected.
I tried to use onclick
and mousedown
in the option
tag that is in this datalist
, but without success.
I need exactly this, not to detect the changes, but to know if the option was selected or not.
Is there a solution ready for this in Javascript?
Note : The second example I gave does not solve my problem because the event detects changes in input
, not datalist > option
.