How to set the focus on a hidden textbox field using JavaScript?

前端 未结 4 1886
自闭症患者
自闭症患者 2020-12-16 10:13

How can I set the focus on a hidden textbox element?

I tried this:

document.getElementById(\"         


        
相关标签:
4条回答
  • 2020-12-16 11:05

    You can add some js if you need a workaround and cannot change the opacity attr.

    /* bind a click handler to your trigger */
    jQuery('#your-search-trigger').on('click', function searchIconEventhandler (event) {
        /* in case your field is fading, cheat a little (check css transition duration) */
        setTimeout ( function timeoutFunction () {
            /* show the cursor */
            jQuery('#your-search-input').focus();
        }, 100);
    });
    
    0 讨论(0)
  • 2020-12-16 11:11

    Using Apsillers answer, my setup for this same situation involved:

    1. a parent div with position:relative;
    2. a child form element position:absolute; z-index:0; opacity:0; filter:alpha(opacity=0);
    3. a second child element position:absolute; z-index: (value > 0) (positioned to cover the transparent input).

    Aspillers' answer is the correct one given the question asked, but I wanted to give a practical example of when this is necessary.

    Specifically, form elements can be hidden if you're using any kind of script/plugin that makes "fancy" inputs (i.e. radio/check elements, select elements). But if your script or plugin is written poorly, it can eliminate keyboard accessibility. Preserving the flow of a form by allowing all elements to have focus can save a lot of headaches for website users.

    0 讨论(0)
  • 2020-12-16 11:12

    If you really need to do this, make the box transparent, not hidden:

    opacity:0;
    filter:alpha(opacity=0);
    

    Alternatively, if you want to ensure that the user doesn't accidentally click it, just place the input inside a div with

    width: 0;
    overflow: hidden;
    

    However, there is most certainly a better way to do what you want, maybe using keydown/keypress events.

    0 讨论(0)
  • 2020-12-16 11:13

    I don't think this is allowed, at least in IE. I got this information from jQuery's focus page.

    0 讨论(0)
提交回复
热议问题