'Jquery - Trigger Keydown not working on mobile

I was trying simulate a keydown event with a value on an input type="telephone" using jQuery. It's working fine on Desktop and iPhone but not in Android Chrome.

$(document).ready(function() {
  simulateKeyEntry('7765443421', $("#txtTelephone"));
});

function simulateKeyEntry(txt, elem) {
  const arryText = Array.prototype.slice.call(txt);
  if (arryText.length > 0) {
    var time = 0;
    
    $.each(arryText, function(index, value) {
      setTimeout(function() {
        $(elem).trigger({
          type: ‘keydown’,
          which: value.charCodeAt(0)
        });
      }, time);
      time += 15;
    });
    
    time = 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input name="txtTelephone" maxlength="14" id="txtTelephone" type="tel" size="14" autocomplete="tel">

I'm using jQuery v1.7.1

Any helps?



Solution 1:[1]

Rather than faking an event, which is notoriously unreliable due to browser security around events being created without user interaction, you can instead update the val() of the element directly within the timer. Note in the example below that I increased the timer delay to 100ms, as 15ms is almost imperceptible.

Also, jQuery 1.7.1 is over 10 years out of date. You should update to the latest version, which at time of writing this comment is 3.6.0

jQuery($ => {
  simulateKeyEntry('7765443421', $("#txtTelephone"));
});

function simulateKeyEntry(text, $elem) {
  const characterDelay = 100;
  let textArray = text.split('');  
  textArray.forEach((char, i) => {
    setTimeout(() => $elem.val((_, v) => v + char), characterDelay * i);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input name="txtTelephone" maxlength="14" id="txtTelephone" type="tel" size="14" autocomplete="tel" />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rory McCrossan