cancel change - set focus to control

20 views
Skip to first unread message

David Elliott

unread,
Aug 25, 2017, 11:36:15 AM8/25/17
to KnockoutJS
I inherited some code which looks like that below.

The issue that I am having is that I would like the control to retain focus on an error.
Currently if you have a text box, enter invalid data and tab off, it goes to the next control
even though the focus was set.  The only way I've found to prevent this is by adding the
yellow highlight.

I have seen the hasFocus binding but that would require that I have an observable variable
for every element  that I have on my page.  I have A LOT of fields.  This approach just doesn't
seem vary feasible to me.

Any thoughts on how to make this work would be appreciated.


<input name="dob" id="dob"
data-bind="DateString: person().dob,
event: {  change: Validation.OnKOChange.bind($data, 'dob') }" >

module xyz {
    export class Validation {
        static OnKOChange = field: string, data: any, event: any): boolean => {
            let rc = true;
            const ctrl = event.currentTarget;
            const lastValue = ctrl.getLastGoodValue();
            switch (field)
            {
                case 'dob': rc = isDateValid(ctrl, lastValue); break;
            }

            // hacky code that works - not currently part of code            
            if (!rc)
                window.setTimeout(() => {ctrl.focus() }, 10);

            return rc;
        }
    }
}
function isDateValid(ctrl, lastValue) {
    const value = ctrl.value  
    const valid = DoSomethingToValidate(value);
    if (!valid) {
        alert ("The date is invalid");
        ctrl.value = lastValue;
        ctrl.focus();
    }
    return valid;
}
Reply all
Reply to author
Forward
0 new messages