Look at this very simple jsfiddle: https://jsfiddle.net/gq9jga4q/33/
<input type="text" id="kbdhook" />
<div id="result" >1: </div>
<div id="result2" >2: </div>
<div id="result3" >3: </div>
$('#kbdhook').keyup(function(event) {
var current = $('#kbdhook').val();
if (current !== '' && current !== '\n') {
var c, l;
for (l = 0; l < current.length; l++) {
c = current[l];
$("#result").html($("#result").html() + c);
}
$("#result2").html($("#result2").html() + " " + $('#kbdhook').val());
$('#kbdhook').val('');
$("#result3").html($("#result3").html() + " " + $('#kbdhook').val());
}
});
My goal is to be able to call a function for every keys typed in an input element.
I'm subscribing to the keyup event and for every letters in it I append them to the document and then clear the text input in order to restart anew the next time.
The #result div is the wanted output that's going to be sent to an external library.
#result2 is used to show that sometimes when you type fast there's multiple letters getting registered in a single keyup event (that's ok).
#result3 is used to show that after clearing the input it is indeed well cleared.
This works perfectly on desktop (IE/Chrome/Firefox) and on iPhone (Safari/Chrome) and also on Android (Firefox). But Chrome on Android give a different behaviour.
Every time the keyup event is triggered, the result of $('#kbdhook').val()
is the value as if the "clearing" $('#kbdhook').val('');
would not have happened. But it did, because #result3 is always blank.
Why such a difference in behaviour between the different browsers, and how could I fix my problem?