I have an input text field on which I trigger key event. On enter, i process some specific code with the input value. All works great.
HAML:
%input#myField{:type => "text"}
JavaScript:
my_field = document.getElementById('myField');
my_field.addEventListener("keypress", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (tag_field.value.length != 0) {
console.log(my_field.value);
// Run my specific process with my_field.value
my_field.value = '';
}
}
}, false);
But now I want to add datalist on this input.
HAML:
%input#myField{:list => "htmlList", :type => "text"}
%datalist#htmlList
%option{:value => "toto"} toto
%option{:value => "foo"} foo
The problem is when I navigate on datalist to select an item, I press the enter key.
On enter key, my listener is called and processes my code with the initial value of input.
At this step, the value of the field is empty. After, the value is replaced by the value selected in the datalist.
So my questions are:
Is there a way to change the behaviour of the datalist to replace the input value by the datalist selected value without pressing enter key? (Disable enter key for datalist)
Is there a way to detect when the datalist is active (or visible) to process a different behaviour in my EventListener ?
Keypress
event will be fired after you press the key but before the data is registered into the field.
Keyup
event will be fired after you press the key but after the data is registered into the field
HTML:
<input list="browsers" id="myField"/>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
</datalist>
JS:
var my_field = document.getElementById('myField');
my_field.addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (my_field.value.length != 0) {
console.log(my_field.value);
// Run my specific process with my_field.value
my_field.value = '';
}
}
}, false);