1

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.

1
  • you can trigger it with something like $("#"+cardNumber).change(); Commented Sep 24, 2021 at 6:47

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

You are my hero !!!
:) Moz has a very nice article to explain this! worth a read ! developer.mozilla.org/en-US/docs/Web/Events/…
0

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">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.