In Javascript find if a checkbox is focused

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.


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.

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

<script type="text/javascript">

var isFocused = false;


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

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.

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.

    <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!' :;


<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">


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


Need Your Help

WPF Validation Manually Adding Errors into Validation.Errors Collection

wpf validation

Is there any way to manually/dynamically add errors to the Validation.Errors collection?

GAC Scope: why does it override local assemblies, and is there anything we can do about it?

.net visual-studio gac

I've spent some time struggling with the GAC today, as a result of it superceding the local assembly in my application directory, and I thought it was odd that the GAC would "rank" a local file; in

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.