0

I want to focus an input field in the document's KeyDown event if it's not already focused. In case that it is already focused, nothing is supposed to happen. If it's not focused yet, the text content is to be deleted and the pressed key – if its char code is in a specific range – to be added.

My current code only works in the newest browsers, not even in Firefox 3.0 for example ...

$(document).keydown(function (e) {
    var code = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

    if (code < 33 || code > 256) {
        return;
    }

    // Check if the text input is focused
    if ($("*:focus").attr("id") == "searchString") {
        // Maybe more to come here ...
    }
    else {
        // Clear content and focus                    
        $("#searchString")
            .val("")
            .focus();
    }
});
1
  • Instead of e.charCode or e.keyCode, try using e.which which is normalized in jQuery Commented Oct 2, 2010 at 14:34

1 Answer 1

1

You can use document.activeElement and check it's id property, like this:

$(document).keydown(function (e) {
    //e.which is normalized by jQuery already
    if (e.which < 33 || e.which > 256) return;
    if (document.activeElement && document.activeElement.id == "searchString") {
      //do stuff
    }
    else {
        $("#searchString").val("").focus();
    }
});

Also you can switch to the event.which property since it's already normalized by jQuery internally.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.