Solution 1 :

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"

Solution 2 :

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() { ... });


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

Solution 3 :

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>
    /* 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

Problem :

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?


Comment posted by germanio

you mean, the input is filled from somewhere else when you click the button?

Comment posted by Triby

Just create a function and call it when the button is clicked.

Comment posted by Tanner Dolby

@avocado So when a

Comment posted by avocado

@germanio, yes, there is a button, if I click it, then the value in the

Comment posted by avocado

@TannerDolby, correct!

Comment posted by avocado

However the button is not written in the html, but generated by some other js code when the html document is loaded, looks like hard to attach new functions to the button if I don’t want to look into the js code.

Comment posted by well-formed quetion

So, please post

Comment posted by avocado

Yes, this sounds like a way to do it. However the button is not written in the html, but generated by some other js code when the html document is loaded.

Comment posted by David Miner

Is there no way through a css selector to attach an event listener to this button? You can possibly css select the button as a child of an element that’s easier to locate. I assume you’re not able to access the javascript that creates the button to address the issue there – that would be the most organic approach.


Leave a Reply

Your email address will not be published. Required fields are marked *