I want to auto fill an input area with javascript. When i fill it with organic key press, this input's event listener trigger another list which is releated what input is. But when i say:
document.getElementById('CardNumber').value = "123"
it does not trigger anything. image
So how can i trigger this "keyup" event listener? Any suggestion is accepted.
CodePudding user response:
Maybe, you can dispatch a keyup
event whenever you are setting a new value yourself
const keyupEvent = new Event('keyup')
cardNumber.dispatchEvent(keyupEvent)
// document.getElementById("CardNumber").value = "123"
const cardNumber = document.getElementById("CardNumber");
cardNumber.addEventListener("keyup", keupLister)
function keupLister(e) {
console.log('keyup fired',e.target.value);
}
setTimeout(() => {
cardNumber.value = "123";
const keyupEvent = new Event('keyup')
cardNumber.dispatchEvent(keyupEvent)
}, 5000)
<input id="CardNumber" placeholder="Try this input">
CodePudding user response:
Since you're using keyup
event-listener, you can raise new Event("keyup")
by using dispatchEvent
from the function where you are changing the value of element.
Reference - See the documentation here and here.
const element = document.getElementById('username');
element.addEventListener("keyup", (e) => {
console.log(e.target.value);
}, false);
function changeValue() {
document.getElementById('username').value = '123';
element.dispatchEvent(new Event("keyup"));
}
<input type="text" id="username" name="username" placeholder="Enter username" />
<br />
<br />
<button onclick="changeValue()">Change value inside username</button>