user666605
user666605

Reputation: 47

Why the onload focus doesn't work on this script?

This is a sample of my form. when the page loads the focus must be on 'fbox' but it dosent work and i don understand why. the form contains a niceditor but i dont think that is the problem

<html>
<head></head>
<body onload="document.form.fbox.focus();">
<body>
<form method='post' action='' name='form' >
Headline <input name='fbox' type='text' class='form' id='box' autocomplete='off' size='80'><br>
Your text</font><br><script type="text/javascript" src="nicEdit.js"></script><script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script>
<textarea name="description" style="width: 100%; height:200px;"></textarea></p>     
<p><select name='catg' >
<option value='' selected >Select category</option>
</select>
<input type="submit" id='button' name="Submit" value="Submit" class="button"></form>
</body></html>

thanks

Upvotes: 0

Views: 2667

Answers (2)

Pointy
Pointy

Reputation: 414006

You've got two body tags. I suggest getting rid of one of them and seeing if that helps.

There's also a stray closing </font> tag in the middle of that code. Many people try to arrange their markup so that it's easy to read and to see the structure of the document. You might want to explore that practice.

Another possibility is that your "nicEdit" plugin is un-doing the ".focus()" call. Try taking that out and seeing if the focus works (as an experiment). If that's happening, then you can do your "focus()" call after the nicEdit code has finished:

bkLib.onDomLoaded(function() {
  nicEditors.allTextAreas();
  document.form.fbox.focus();
});

(That's an adaptation of the code in your existing <script> block.)

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114427

You have two body elements. That won't work.

Scripts run top-to-bottom, so you're firing the "onload" before the rest of the page has rendered. It's likely the element you are trying to focus is not there when the event fires.

There are a number of ways to fix this. jQuery has a handy method that waits until the DOM is ready.

A simple way is simply to run your script from the bottom of the page in a script block.

<script type="text/javascript">
document.form.fbox.focus()
</script>

Upvotes: 0

Related Questions