Programmatically triggering events in Javascript for IE using jQuery

When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.event object (as far as I know)

This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the window.event object stores the last user-triggered event.

When the onchange event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.

Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.


To explain what I'm doing specifically:
I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.

The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's change() method.

Because the trigger for the event was a list item, IE sees the list item as the source of the event, not the text box, like it should.

I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "change" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.

Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?


I've found this problem reported several other places, but they offer no solutions:

Answers:

Answer

I had the same problem. Solved by using this function:

jQuery.fn.extend({
    fire: function(evttype){ 
        el = this.get(0);
        if (document.createEvent) {
            var evt = document.createEvent('HTMLEvents'); 
            evt.initEvent(evttype, false, false); 
            el.dispatchEvent(evt); 
        } else if (document.createEventObject) { 
            el.fireEvent('on' + evttype); 
        }
        return this;
    }
});

So my "onSelect" event handler to datepicker looks like:

if ($.browser.msie) {
    datepickerOptions = $.extend(datepickerOptions, { 
        onSelect: function(){
            $(this).fire("change").blur();
        }
    });
}
Answer

I solved the issue with a patch:

    window.ValidatorHookupEvent = function(control, eventType, body) {
        $(control).bind(eventType.slice(2), new Function("event", body));
    };

Update: I've submitted the issue to MS (link).

Answer

From what you're describing, this problem is likely a result of the unique event bubbling model that IE uses for JS.

My only real answer is to ditch the ASP.NET validators and use a jQuery form validation plugin instead. Then your textbox can just be a regular ASP Webforms control and when the contents change and a postback occures all is good. In addition you keep more client-side concerns seperated from the server code.

I've never had much luck mixing Webform Client controls (like the Form Validation controls) with external JS libraries like jQuery. I've found the better route is just to go with one or the other, but not to mix and match.

Not the answer you're probably looking for.

If you want to go with a jQuery form validation plugin concider this one jQuery Form Validation

Answer

Consider setting the hidden field _EVENTTARGET value before initiating the event with javascript. You'll need to set it to the server side id (replace underscore with $ in the client id) for the server to understand it. I do this on button clicks that I simulate so that the server side can determine which OnClick method to fire when the result gets posted back -- Ajax or not, doesn't really matter.

Answer

This is an endemic problem with jQuery datepickers and ASP validation controls. As you are saying, the wrong element cross-triggers an ASP NET javascript validation routine, and then the M$ code throws an error because the triggering element in the routine is undefined.

I solved this one differently from anyone else I have seen - by deciding that M$ should have written their code more robustly, and hence redeclaring some of the M$ validator code to cope with the undefined element. Everything else I have seen is essentially a workaround on the jQuery side, and cuts possible functionality out (eg. using the click event instead of change).

The bit that fails is

   for (i = 0; i < vals.length; i++) {
        ValidatorValidate(vals[i], null, event);
    }

which throws an error when it tries to get a length for the undefined 'vals'.

I just added

if (vals) {
    for (i = 0; i < vals.length; i++) {
        ValidatorValidate(vals[i], null, event);
    }
}

and she's good to go. Final code, which redeclares the entire offending function, is below. I put it as a script include at the bottom of my master page or page.

Yes, this does break upwards compatibility if M$ decide to change their validator code in the future. But one would hope they'll fix it and then we can get rid of this patch altogether.

//  Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix
 function ValidatorOnChange(event) {
    if (!event) {
        event = window.event;
    }
    Page_InvalidControlToBeFocused = null;
    var targetedControl;
    if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
        targetedControl = event.srcElement;
    }
    else {
        targetedControl = event.target;
    }
    var vals;
    if (typeof (targetedControl.Validators) != "undefined") {
        vals = targetedControl.Validators;
    }
    else {
        if (targetedControl.tagName.toLowerCase() == "label") {
            targetedControl = document.getElementById(targetedControl.htmlFor);
            vals = targetedControl.Validators;
        }
    }
    var i;
    if (vals) {
        for (i = 0; i < vals.length; i++) {
            ValidatorValidate(vals[i], null, event);
        }
    }
    ValidatorUpdateIsValid();
}
Answer

This is how I solved a simlar issue. Wrote an onSelect() handler for the datepicker. link text In that function, called __doPostBack('textboxcontrolid',''). This triggered a partial postback for the textbox to the server, which called the validators in turn.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.