Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Events: hooking on value change event on text inputs

I have a text input whose content is changed by a script not by user. So I would want to fire an event when the value changes. I can't find a suitable event for that. I even found this on StackOverflow, but it is not the solution I'm looking for.

How to make this work with jQuery and a text input where the value is set like this:

myTextControl.value = someValue

Here I want to fire an event to see the new value.

like image 709
Esteban Feldman Avatar asked Dec 04 '09 15:12

Esteban Feldman


People also ask

How do you trigger an event when a textbox is filled with value?

change function , but that needs to be done only if the the value is changed using the button . $("#address"). change will trigger if you perform any change in text field. If you want to trigger alert only when button click why you don't use alert inside button click function.

What event can you listen to when the value is changed by JavaScript?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event.

Which JavaScript events are applicable on input component?

The input event fires when the value of an <input> , <select> , or <textarea> element has been changed. The event also applies to elements with contenteditable enabled, and to any element when designMode is turned on. In the case of contenteditable and designMode , the event target is the editing host.


2 Answers

I can't find a suitable event for that.

Yeah, there isn't one.

There are DOM Mutation Events, but they aren't supported well cross-browser, and don't fire for form values anyway as those aren't reflected in attributes (except in IE due to a bug).

In Mozilla only, a JavaScript watch could be set on the value property to catch scripted changes. In IE only, a JScript onpropertychange handler could be set to catch both scripted and user-driven changes. In other browsers you would have to use your own interval poller to look for changes.

function watchProperty(obj, name, handler) {
    if ('watch' in obj) {
        obj.watch(name, handler);
    } else if ('onpropertychange' in obj) {
        name= name.toLowerCase();
        obj.onpropertychange= function() {
            if (window.event.propertyName.toLowerCase()===name)
                handler.call(obj);
        };
    } else {
        var o= obj[name];
        setInterval(function() {
            var n= obj[name];
            if (o!==n) {
                o= n;
                handler.call(obj);
            }
        }, 200);
    }
}

watchProperty(document.getElementById('myinput'), 'value', function() {
    alert('changed!');
});

This is highly unsatisfactory. It won't respond to user-driven changes in Mozilla, it allows only one watched property per object in IE, and in other browsers the handler function will get called much later in execution flow.

It's almost certainly better to rewrite the parts of script that set value to call a setValue wrapper function instead, that you can monitor for changes you want to trap.

like image 119
bobince Avatar answered Oct 03 '22 07:10

bobince


You can add a normal event listener to your input field like so. (using jQuery)

$(myTextControl).change(function() {
    ...
    /* do appropriate event handling here */
    ...
});

Ok considering that the javascript which changes the input value isn't controlled by you it gets difficult. You are left with two options:

1.) Crossbrowser compatible: Implement polling of input value with a function which continuously checks if the value changed. (Something along these lines).

//at beginning before other scripts changes the value create a global variable
var oldValue = myTextControl.value;

function checkIfValueChanged() {
    if(myTextControl.value != oldValue) {
        $(myTextControl).trigger("change");
        clearInterval(checker);
    }
}

//every 500ms check if value changed
var checker = setInterval('checkIfValueChanged()', 500);

Note: If your script or the user can change the value too you must implement something to catch this in order not to trigger the change event multiple times.

If the value can change multiple times by the external script just let the interval function run instead of canceling it and just update oldValue;

2.) AFAIK Not supported yet by all browsers (? test it on the ones you need to support)

You could bind to a special DOM Level 3Event: DOMAttrModified (in Firefox, maybe others too I think Opera has it too, Safari??, Chrome??) and in IE of course it has a different name propertychange (and is proprietary and different from the W3C behavior)

Now ideally you could combine the two options and check if support for DOMAttrModified or propertychange is there and use accordingly or fallback to the polling solution.


Reading links

W3C DOM Mutation Events

W3C DOMAttrModified Event

MSDN DHTML propertychange Event

jQuery CSS Property Monitoring Plug-in updated

Last link is some guy which basically already made a jQuery plugin doing the things described by me (untested by me, provided just as a reference)

like image 6
jitter Avatar answered Oct 03 '22 08:10

jitter