views:

193

answers:

2

Hi,

Basically I need to check if the value is changed in a textbox on the 'blur' event so that if the value is not changed, I want to cancel the blur event.

If it possible to check it the value is changed by user on the blur event of an input HTML element?

Thanks,

+2  A: 

I don't think there is a native way to do this. What I would do is, add a function to the focus event that saves the current value into a variable attached to the element (element.oldValue = element.value). You could check against that value onBLur.

Pekka
+1  A: 

You can't cancel the blur event, you need to refocus in a timer. You could either set up a variable onfocus or set a hasChanged variable on the change event. The blur event fires after the change event (unfortunately, for this situation) otherwise you could have just reset the timer in the onchange event.

I'd take an approach similar to this:

(function () {
    var hasChanged;
    var element = document.getElementById("myInputElement");
    element.onchange = function () { hasChanged = true; }
    element.oblur = function () {
        if (hasChanged) {
            alert("You need to change the value");

            // blur event can't actually be cancelled so refocus using a timer
            window.setTimeout(function () { element.focus(); }, 0);          
        }
        hasChanged = false;
    }
})();
Andy E