Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immediately detect changes in an <input type="text"> modified by JavaScript [duplicate]

Tags:

javascript

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.

like image 424
Key-Six Avatar asked Oct 04 '22 02:10

Key-Six


1 Answers

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

like image 200
Retsam Avatar answered Oct 12 '22 12:10

Retsam