简体   繁体   中英

How to capture input changes event using Javascript?

Given an input element, I know we can use this to capture input changes,

$("input").on("change", function() { ... });

So that, when users type text in the input box, the above function will be triggered.

However, my use-case is that, the input is being updated by a button click, not by user typing text directly. And seems cannot use the above code to capture the input changes event.

Any other approaches?

You need to bind your button with your field by updating the value attribute inside the button callback function. Then use the value wherever.

const button = document.getElementById("btn");
const field = document.getElementById("field");

button.addEventListener("click", event => {
  // Update your input attrs here
  field.value = "Updated"
})

How about attaching a 'click' event listener to the button, and reading or modifying the input box according in that event handler?

$("button").on("click", function() {... });

or

$("button").click(function() {... });

Since you have said that you are generating the button with js, you could add the event listener while the button is being generated:

<div id="app"></div>
<script>
    /* inside your code to generate your button */
    var btn = document.createElement("button"); // your code to generate the button
    var app = document.getElementById("app").appendChild(btn); // the code to add the button to the document 
    btn.addEventListener('click', function() {console.log("It works!")}); // add an event listner to the button while you still have a reference to it
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM