I have a simple html page and when I load it in Google chrome I want the cursor to go into the single textarea. This isn't working -- here's what I have
<html>
<body OnLoad="document.box.focus()">
<textarea name="box" rows="2000" cols="80">
</textarea>
</body>
</html>
And it seems it can't figure out what element I'm talking about:
Uncaught TypeError: Cannot call method 'focus' of undefined
What's the correct way to do this?
Use an id
and getElementById
:
<html>
<body OnLoad="document.getElementById('theTextBox').focus()">
<textarea id="theTextBox" name="box" rows="2000" cols="80">
</textarea>
</body>
</html>
Chrome doesn't clutter the global namespace with name
values (and the global namespace is on window
rather than document
).
Technically, you can do this:
<html>
<body OnLoad="window.theTextBox.focus()">
<textarea id="theTextBox" name="box" rows="2000" cols="80">
</textarea>
</body>
</html>
...because id
s get dumped into the global namespace (it's even being specified by the W3C that way, sadly). But you can get collisions in that namespace (for instance, if you had a var theTextBox;
), whereas getElementById
is meant to work directly with id
values.
You get that error message because you can't access a DOM element by name as a property of the document
object. You should be using document.getElementsByName() to access an array of all the elements sharing a given name (in your simple case you'd use document.getElementsByName('box')[0].focus()
to access the single textarea
).
Alternatively and preferably you should set some ID on that element (like <textarea id="box" rows="2000" cols="80" ...>
) and then access the element using document.getElementById() so that you always get precisely one element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.