We help IT Professionals succeed at work.

show a field and set focus to that field

Gary Samuels
Gary Samuels asked
on
I have several input text fields that are hidden.  When a button is clicked it calls:

function showlines(index) {
            $( "div.attwrapper" + index).toggleClass( "show-field", 500, "linear"  );
            document.getElementById( "div.attwrapper" + index).focus();
            break;
}


The document.getElementById was my attempt to set focus on the text field within the div.attwrapper .
It doesn't work, anyone know how I can set the focus on the text field?
Comment
Watch Question

Top Expert 2013
Commented:
You need to use getElementsByTagName to get an array of elements of type "input" within your div. Then just pick the first one and set the focus:
    var div = document.getElementById( "div.attwrapper" + index);
    var txtBoxes = div.getElementsByTagName('input');
    if(txtBoxes.length) > 0
        txtBoxes[0].focus();

Open in new window

If you have more than one "input" elements in the div you may need to check their types to make sure they are not checkboxes or buttons:
    var div = document.getElementById( "div.attwrapper" + index);
    var txtBoxes = div.getElementsByTagName('input');
    for(var i = 0; i < txtBoxes.length; i++) 
    {
        if (chk[i].type == 'text') 
        {
            txtBoxes[0].focus();
        }
    }

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
You're trying to get an element by id, by passing in a class! It won't work.

Take a look at this:

function showlines(index) {
    var div = $('div.attwrapper'+index);
    div.toggleClass("show-field", 500, "linear");
    $('input[type=text]', div).focus()
}

Open in new window