[Web] Focus on first visible control

Discussion in 'Javascript' started by Paul E Collins, Jan 7, 2005.

  1. I have a Web form with a number of text boxes. If the user submits the
    page with some text boxes filled in, those then become plain text
    (with accompanying <input type="hidden"> fields for when the page is
    resubmitted) - so the number of text boxes varies.

    I was using this to focus on the first text box:

    <body onLoad="document.forms[0].elements[0].focus();">

    But it doesn't work when the first text box has been removed. In
    effect, the browser is setting the focus to the new first control
    (with type="hidden") so the caret is not visible.

    How can I focus on the first *visible* input element?

    Paul E Collins, Jan 7, 2005
    1. Advertisements

  2. Paul E Collins

    sunami Guest

    you can test if the controle/element is of type == "text".
    sunami, Jan 7, 2005
    1. Advertisements

  3. Paul E Collins

    Lee Guest

    Paul E Collins said:
    Whatever server-side code you're using to create the hidden fields "knows" which
    is the first visible field. Have it modify the onload handler accordingly.
    Lee, Jan 7, 2005
  4. Oh, I've found a solution myself.

    I'm using the 'type' property to check that an input is 'text' (and
    not, say, 'hidden').

    function focusFirstVisibleInput()
    var d = document.forms[0];
    for (var i = 1; i <= d.elements.length; i++)
    var e = d.elements['a' + i];
    if (e.type == 'text')

    Paul E Collins, Jan 7, 2005
  5. Paul E Collins

    Mick White Guest

    I would start from 0(zero).
    Mick White, Jan 7, 2005
  6. Paul E Collins

    Lee Guest

    Mick White said:
    and end at the last element, even though you should
    never actually get past it in this application:

    for (var i = 0; i < d.elements.length; i++)
    Lee, Jan 8, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.