I would like to immediately detect changes in an input type="text" when it's modified by JavaScript. When it's changed manually by user the detection can be triggered by:
onchange="myfunction();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"
I just can't figure this one out.
As you've said that you control the code that changes it, you might simply trigger a change event when you change the contents of the input. In jQuery it'd be:
var textinput = //Perhaps $("input[type='text']") or $("#someid")
textinput.val("New text here");
textinput.trigger("change");
And that would trigger whatever function you bound to your onchange event.
If you're doing this often enough, you may just want to make a function that updates the value and triggers the event.
Without jquery, it's a little more complicated, but take a look at How can I trigger an onchange event manually?
EDIT:
Here's a complete example, again using jQuery. Note that I'm using javascript to set up handlers, rather than actually specifying them in HTML, as this is the better practice, generally speaking.
HTML:
<input type="text" id="toChange">
Javascript:
function changeFunction() {
//Do whatever
}
$(document).ready(function() {
var inputbox = $("#toChange");
inputbox.on('change', changeFunction);
inputbox.on('paste', changeFunction);
//Can attach other functions, though beware of multiple triggers
});
//SetTimeout in place of whatever code does the changing
window.setTimeout(function() {
var inputbox = $("#toChange")
inputbox.val("Set by function");
inputbox.trigger("change");
}, 3000);
JFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With