admin管理员组

文章数量:1429486

I have a list of inputs under a list of divs respectively. I have a button that when clicked it will switch one input from from not display to display. This is something like:

if (switched) {
        document.getElementById("div-xxx").style.display = "block";
}

However, is there a way I could make the input inside the displayed div being auto focused after this switch? I tried something like

document.getElementById('input-xxx').autofocus = true;

after the display code, but there is no autofocus at all.

I have a list of inputs under a list of divs respectively. I have a button that when clicked it will switch one input from from not display to display. This is something like:

if (switched) {
        document.getElementById("div-xxx").style.display = "block";
}

However, is there a way I could make the input inside the displayed div being auto focused after this switch? I tried something like

document.getElementById('input-xxx').autofocus = true;

after the display code, but there is no autofocus at all.

Share Improve this question edited Oct 23, 2019 at 4:01 John M. asked Oct 23, 2019 at 1:00 John M.John M. 9052 gold badges10 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

document.getElementById('input-xxx').focus() will change the focus to the selected element.

document.getElementById('input-xxx').setAttribute('autofocus', true) will assign the autofocus attribute to the html element

object.focus(); will help

if (switched) {
        document.getElementById('div-xxx').style.display = "block";
        document.getElementById('input-xxx').focus();
}

The only thing that worked for me was

    if (switched) {

        document.getElementById('div-xxx').style.display = "block";
        document.getElementById('old-input').setAttribute('autofocus', false);
        document.getElementById('input-xxx').setAttribute('autofocus', true);
        document.getElementById('input-xxx').focus();
}

本文标签: javascriptHow to autofocus after changing display from none to blockStack Overflow