Focus on element not working correctly

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Here is the scenario. I have an alert that fires if the user has not
filled in a field.  What I would like to do is have the browser focus
on the message (div id="message").  That div is generated only if
there is an error, and the server side code is placed within the
head.  What I think is happening is the js focus is firing BEFORE the
div is rendered, because I am getting the js error
document.getElementById("") is null or is not an object.  This is not
something vital, just something I think would be nice for the user
(especially if the form and message are below the fold).  I have
included code and markup below.  (no URL - this is stripped down to
what's necessary).

<% option explicit%>
<!--#include file="docheader_inc.asp"-->
dim fname, isget

if request.servervariables("REQUEST_METHOD") = "POST" then
   ispost = true
elseif request.servervariables("REQUEST_METHOD") = "GET" then
   isget = true
end if

 if ispost then %>
       if request.form("fname") = "" then
            required = "fname"
            message = "First name is required"
       end if

if message <> "" then
      <script type="text/javascript">
<% message = "<div id=" & chr(034) & "message" & chr(034) &
"><strong>" & message & "</strong></div>"

end if

     fname = "Your first name"

end if%>
<style type="text/css">
.required, #required {
<% if required <> "" then%>
#<%=required%>1 {
    background-color: yellow;
#<%=required%> {
     background-color: pink;
     color: black
<% end if%>
<form method="post" action="<%=request.servervariables("script_name")
<fieldset><legend>* indicates <span class="required">Required</span>
<label for="fname" id="fname1" class="required">First Name </label>
<input type="text" name="fname" id="fname" value="<%=fname%>" <%if
isget then%>onfocus="if(this.value == '<%=fname%>') this.value = '';"<
%end if %>><br>
<label for="lname" id="lname1">First Name </label> <input type="text"
name="lname" id="lname" value="<%=lname%>" <%if isget then
%>onfocus="if(this.value == '<%=lname%>') this.value = '';"<%end if
<p><input type="submit" value="Submit"></p>

Re: Focus on element not working correctly

Quoted text here. Click to load it

A div can't hold the focus, it isn't something the user can interact

Quoted text here. Click to load it

Well yes. The <script> element tries to access the element, but since
the element doesn't start until after the <script>, it doesn't exist
at that moment.

You would have to move the script so it doesn't fire until the element
exists ... but a div still couldn't hold the focus.

David Dorward / /

Site Timeline