How to re-focus to a text field when focus is lost on a HTML form?

前端 未结 3 1729
梦谈多话
梦谈多话 2021-01-13 04:48

There is only one text field on a HTML form. Users input some text, press Enter, submit the form, and the form is reloaded. The main use is barcode reading. I use the follo

3条回答
  •  星月不相逢
    2021-01-13 05:28

    You can hook the blur event and refocus the field again. There are very few use cases for doing this, but it sounds like yours may be one of them. Note that you'll probably have to schedule the re-focus via setTimeout or similar, you won't be able to do it within the blur handler itself.

    When doing this without affecting the markup, this is easiest if you use a library like Prototype, jQuery, Closure, etc., but you can do it without them (of course), you just have to handle browser differences yourself. For instance, using Prototype:

    document.observe("dom:loaded", function() {
        var elm = $('thingy');
    
        elm.focus();
        elm.observe('blur', function() {
            refocus.defer(elm);
        });
    
        function refocus(elm) {
            elm.focus();
        }
    });
    

    If you don't mind affecting the markup, you can use the onblur attribute. For instance, this works on IE, Firefox, and Chrome at least (probably others):

    HTML:

    
    

    Script:

    function refocus(elm) {
    
        setTimeout(go, 0);
    
        function go() {
            elm.focus();
        }
    }
    

提交回复
热议问题