Javascript - Event trigger when text input change but not with physical key board

Viewed 47

I have created a virtual numeric keypad by Javascript that appears when the user focuses on input (by onfocus event). When clicking on this keypad buttons can type in that input. In this input another function runs by onkeyup event which means when the user types in this input by physical keyboard this function triggers.

<input type="text" id="nc" onkeyup="checkNationalCode(this);" onfocus="appearNumPad(this);"/>

The problem here:

When the user types by clicking on my virtual numeric keypad, onkeyup event doesn't trigger. I have tried some other event types instead onkeyup (for example onchange, oninput ,...) but non of them work.

Is there any event type that triggers and runs checkNationalCode() function when the user clicks on the keypads button (typing on the keypads button in input) or another why two run this function by user typing with my virtual keypad?

I can not use onclick event on the keypad buttons because checkNationalCode() is in one of my input but my virtual keypad is used for all of input.

The function that creates and appears on my keypad by ajax :

function appearNumPad(obj){
    document.getElementById("numPadContainer").style.display = "block";
    //step1:
    let request = new XMLHttpRequest;
    //step2:
    request.open("GET", "../common/numPad.php?inputID="+obj.id);
    //step3:
    request.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("numPadContainer").innerHTML=this.responseText;
        }
     };
    //step4:
    request.send();
}
1 Answers

Inside your virtual keypad key click handler, you could dispatch your desired event to the input like this.

const input = document.querySelector('#nc');
input.dispatchEvent(new KeyboardEvent('keyup', {'key': '<key name>'}));
Related