How to auto-focus after changing display from none to block?

Viewed 1123

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.

3 Answers

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();
}

Related