简体   繁体   中英

How do i get this script to focus an element on keydown/keypress?

How do i get this script to work? i want it to focus the element with the id "order_number" on ctrl or alt keypress/keydown. I'm sure i wrote it wrong but i'm hoping i'm not terribly off.

function setFocusToTextBox(field, evt) {
    if (evt.keycode === 17) {
        if (evt.preventDefault) {
            evt.preventDefault();
        } else if (evt.stopPropagation) {
            evt.stopPropagation();
        } else {
            evt.returnValue = false;
        }
        getElementById("order_number").focus();
        return false;
    } else {
        return true;
    }
}

I cleaned up the code with the suggestions from my comment.

function setFocusToTextBox(evt) {
    if (evt.ctrlKey || evt.altKey) {
        if (evt.preventDefault)
        {
            evt.preventDefault(); //prevent the default action for the ctrl and alt keys.
        }
        document.getElementById("order_number").focus();
        return false;
    } else {
        return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM