简体   繁体   中英

keep focus on text input field if another input field is not clicked

I am trying to create an onblur event where any time some one clicks anywhere on the page it will stay focused on that element unless it is a specif element then it will refocus to that specific element. I am probably way off but this is what I tried, and it just stays focused on the Barcode element no matter what.

function stayOnBarcode() {
    var QTY = document.getElementById("QTY");
    var Barcode = document.getElementById("Barcode");
    if (Barcode.value === "") {
        if (QTY.focus() === true) {
            QTY.focus();
        }
        else if (document.hasFocus() === true) {
            Barcode.focus();
        }
    }
    else {
        Barcode.focus();
    }
}

How about something like this:

$(document).on("mousedown", function(e) {
    clicked = $(e.target)
})

$("input").on("blur", function() {
    if (!clicked.is("#QTY") && !clicked.is("#Barcode")) {
        $(this).focus()
    }
})

It stores the most recently clicked element in the variable clicked , then on blur event it checks if last_clicked is something other than #QTY or #Barcode . If so, it re-focuses the input being blurred.

You might need to tweak it to fit the exact conditions you have in mind, or feel free to add specifics to your question.

Check out this working fiddle: https://jsfiddle.net/oez0488h/63/

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