that are modified by JavaScript I would like to immediately detect changes in the input type = ...">

Detect immediately changes to <input type = "text"> that are modified by JavaScript

I would like to immediately detect changes in the input type = "text" when it was changed by JavaScript. When changing manually by the user, the user can detect a trigger:

onchange="myfunction();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" 

I just can't figure it out.

+4
source share
2 answers

As you said that you control the code that changes it, you can simply raise a change event when the contents of the input change. In jQuery, this will be:

 var textinput = //Perhaps $("input[type='text']") or $("#someid") textinput.val("New text here"); textinput.trigger("change"); 

And that will call any function related to your onchange event.

If you do this often enough, you can simply create a function that updates the value and fires the event.

Without jquery, this is a little trickier, but see How can I fire the onchange event manually?

EDIT:

Here is a complete example using jQuery again. Note that I use javascript to set up handlers, not to specify them in HTML, as this is best 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

+3
source

You can use the MutationObserver object, which allows you to observe changes in attributes. However, I'm not sure if the feedback is called when you execute el.value = ... instead of el.setAttribute('value', ...) .

You can also define a custom installer for the value property using Object.defineProperty . However, I have never done this on a DOM element, and if it is already installed, you might want to make sure that your new setter also names it. You can use Object.getOwnPropertyDescriptor to get the current setter, if any.

Finally, as a last resort, you can always use setInterval to periodically check to see if the value property of an element has changed, but I don't really like this approach. However, this may be the only cross-browser.

Unfortunately, I cannot verify this right now, but I will come back and update this answer later.

+1
source

Source: https://habr.com/ru/post/1499705/


All Articles