views:

1955

answers:

4

In Javascript how can I tell if a checkbox has focus or not?

I thought there would be a method or property called isfocused. But apparently not.

By in focus I mean they've tabbed to it using the keyboard and at this point pressing space would check the box.

+1  A: 

There is a onfocus event that fires when an element receives focus.

<script type="text/javascript">

var isFocused = false;

</script>

<input type="checkbox" name="team" value="team" onfocus="javascript:isFocused = true;">Spurs<br>
regex
+3  A: 

Create an event handler that is wired to the onfocus event. When it's called, set a global var to remember that it's got the focus. Write another one on the onblur event which clears the variable.

Denis Hennessy
+1  A: 

You might have to just hook into the onfocus and onblur events for the checkbox to keep track of when it gets and loses focus.

Marc Novakowski
+1  A: 

Here's an example of the basics of an implementation that might help you. Note: the output stuff is just for demonstration purposes and not part of the actual solution.

<html>
<head>
    <script type="text/javascript">

    onload = function()
    {
     var f = document.forms.test;
     f.focusedElem = null;
     updateOutput( f );

     for ( var i = 0, l = f.elements.length, elem; i < l; i++ )
     {
      elem = f.elements[i];
      elem.onfocus = function( elem )
      {
       return function()
       {
        elem.form.focusedElem = elem;
        updateOutput( elem.form );
       }
      }( elem )

      elem.onblur = function()
      {
       f.focusedElem = null;
       updateOutput( f )
      }
     }
    }

    function updateOutput( f )
    {
     document.getElementById( 'output' ).innerHTML = ( null == f.focusedElem ) ? 'Nothing!' : f.focusedElem.id;
    }

    </script>
</head>
<body>

<form name="test">

<input type="checkbox" name="foo" id="foo1">
<input type="checkbox" name="foo" id="foo2">
<input type="checkbox" name="foo" id="foo3">
<input type="checkbox" name="foo" id="foo4">

</form>

What has focus? <span id="output"></span>

</body>
</html>
Peter Bailey