Setting FOCUS on HTML element with JavaScript

Discussion in 'HTML & Website Design' started by info@asgardforge.com, Feb 24, 2010.

  1. #1
    A very simple problem - to set focus on a form element when "Submit" is clicked. And I've read the same answers most places I've looked - including here, a post from 2007.

    Problem is, it doesn't work for me. I'm obviously missing something. Here's my simplified code:

    
    <script type="text/javascript">
    function myFocus() {
    	document.form1.visitor.focus();
    	document.form1.visitor.style.background = "red";
    	return false;
    }
     function function2() {
    	alert("onFocus event has been fired");
    }
    </script>
    </head>
    <body>
    
    <form id="form1" action="" enctype="multipart/form-data" method="post">
    NAME: 
    	<input id="visitor" name="visitor" type="text" onFocus="function2()" />
    	<input type="submit" value="Submit" onclick="myFocus()" />
    </form>
    
    Code (markup):
    I don't get any errors in FF or I.E., it just doesn't do anything when I click submit. No cursor in the 'visitor' element, no red background. I'm trying this locally on my computer, as well as on a node in a Drupal website. Both places, it does nothing. ??
     
    info@asgardforge.com, Feb 24, 2010 IP
  2. info@asgardforge.com

    info@asgardforge.com Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    UPDATE:
    I've revised my script as follows:
    
    function myFocus() {
    	theFocus = document.getElementById("visitor");
    	theFocus.focus();
    	theFocus.style.background = "red";
    }
    (form remains the same)
    <form id="form1" action="" enctype="multipart/form-data" method="post">
    NAME: 
    	<input id="visitor" name="visitor" type="text" style="background-color:gray" />
    	<input type="submit" value="Submit" onclick="myFocus()" />
    </form>
    
    Code (markup):
    And that works - sort of. The focus goes to that element, and it turns red, for only a quick second and then it's gone. In FF and IE. Any idea why?
    ..
     
    info@asgardforge.com, Feb 25, 2010 IP