1

Is it possible to register an event for changing html input value in javascript?

I mean I have an input. And when I type into it an event is registered, but when I update its (inputs) value through javascript the input event is not called. What is a workaround here?

For example, when you type into input the resulting text is updated, but when you clear the input using button (in other words through javascript) the input event is not registered.

html

<input id="inpt" oninput="updateText()" />
<div id="txtDiv">
  resulting text
</div>
<button id="btn">
Click
</button>

js

const input = document.getElementById("inpt");
input.addEventListener('input', function() {
  const resultingText = document.getElementById("txtDiv");
  resultingText.innerHTML = input.value;
  alet("called");
});

const btn = document.getElementById("btn");
btn.addEventListener('click', function() {
  input.value = "";
});

fiddle.

7
  • personnally I use the keyup event but it may be bad practice I don't know Commented Aug 23, 2018 at 9:10
  • but I checked your code it is working correctly.and event listener is not registered on user input it is on Dom ready Commented Aug 23, 2018 at 9:11
  • @NullPointer, when you click the button the resulting text should become blank. It does not happen. And I did not tell that the code is not working I provided the code to explain what effect I want to achieve and what I have so far. Commented Aug 23, 2018 at 9:13
  • if you dynamically changing the value of input then you can change the innerHTML of the div also on button click. Commented Aug 23, 2018 at 9:18
  • Ok.In this case input event will not trigger implicitly and you have to do it explicit Commented Aug 23, 2018 at 9:19

1 Answer 1

3

I found out that if you separate the logic in the event listener into its own function, you could just call that function when the button is pressed.

const input = document.getElementById("inpt");
input.addEventListener('input', function() {
  changeText();
});

const btn = document.getElementById("btn");
btn.addEventListener('click', function() {
  input.value = "";
  changeText();
});

function changeText() {
  const resultingText = document.getElementById("txtDiv");
  resultingText.innerHTML = input.value;
  alert("called");
}

JS Fiddle: https://jsfiddle.net/joabysvt/1/

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

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.