1

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.

Ray
  • 45,695
  • 27
  • 126
  • 169
  • Why do you need to know if it 'has focus'? Does that mean they've selected the label next to it? Only 'chec' and uncheck seem to matter. – George Stocker Feb 11 '09 at 00:43
  • In the javascript I'm responding to some keyboard events and I need to know if it's the last checkbox in the list. – Ray Feb 11 '09 at 00:47
  • What happens if they use a mouse? – George Stocker Feb 11 '09 at 00:49
  • Then I don't need to worry about it. It comes down to if they tab past the last checkbox in the list, I need to hide the list. If they use the mouse, the list will be closed anyway. – Ray Feb 11 '09 at 00:51

4 Answers4

4

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
  • 7,243
  • 4
  • 25
  • 31
1

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,585
  • 5
  • 31
  • 41
1

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
  • 44,628
  • 11
  • 58
  • 63
1

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
  • 105,256
  • 31
  • 182
  • 206