views:

1031

answers:

2

I'm trying to achieve the following behaviour in html: user is presented with a form involving several text fields. The fields are populated with default values, but in many cases the user will wish to enter their own. When the page loads, the value in the first field is selected, so the user can either replace it by simply starting to type and tabbing out to the next field, or simply leave it and tab out. Here's a pared down example of what I have:

<html>
    <body onload="document.getElementById('helloField').select()">
        <form>
            <input id="helloField" value="hello"/><br/>
            <input value="goodbye"/><br/>
            <input type="submit" value="Submit"/>
        </form>
    </body>
</html>

This works in Chrome (and Firefox I believe, but I don't have it here). In IE, the field is selected as intended, but when the user hits tab, the browser tabs out to its address bar rather than to the goodbye field. If I replace the select with a simple focus, like

<body onload="document.getElementById('helloField').focus()">

the tabbing is okay in all browsers, but this isn't what I want. I want the user to be able to start typing right away to replace the default value.

Anyone have any ideas?

Thanks.

+1  A: 

Try setting the tab order of the fields using tabindex:

<html>
    <body onload="document.getElementById('helloField').select()">
        <form>
            <input id="helloField" value="hello" tabindex="1" /><br/>
            <input value="goodbye" tabindex="2" /><br/>
            <input type="submit" value="Submit" tabindex="3" />
        </form>
    </body>
</html>
Marius
Unfortunately that didn't work.
jjujuma
+2  A: 

Focus, then select.

Also consider putting the code in a script block directly after the input in question. If you have a bunch of images on the page, document.onload can fire quite a lot later, and the last thing you want is to be typing away in an input box when onload fires and hijacks your focus (making you delete the contents of the box).

<input id="helloField" value="hello"/><br/>
<script type="text/javascript">
    var hello= document.getElementById('helloField');
    hello.focus();
    hello.select();
</script>
bobince