Javascript onfocus / alerts help :)

Associate
Joined
15 Feb 2006
Posts
1,872
Location
hell
Hi guys

I'm trying to learn more about javascript at the moment and am trying to fire an alert every time a form field is focused on.

I've created this code.
Code:
	function setup()
	{
	
	var formfields = document.getElementsByTagName("input");
	formfields[0].addEventListener("focus",fireevent,false);
	
	}
	function fireevent()
	{
	alert(this.id);
	return false;
	}

<body onload="setup()">

I have two problems:

Firstly, the alert fires correctly on the first input... however, when I press OK, it keeps firing! how do I make it only fire once?

Second problem, how can I make it fire on ALL inputs? You'll see I've done the following: formfields[0]. with the [0] indicating the first form input. However, I've only done this, as without selecting one input, it doesn't work at all...

Any help would be greatly appreciated
 
Associate
Joined
14 Apr 2003
Posts
1,101
I think the first problem is to do with the alert. When the alert shows focus is taken away from the input - when you click ok it is given back to the input, forcing another alert... and so on. You could try logging to the console instead? console.info("input focussed"); and then checking the console while you switch between inputs.

Secondly, assuming you dont want to use jQuery or similar, I don't think there is an easy solution, you will have to loop through each input in the form. I'm not too sure about the best way to do this though so someone with better JS knowledge will have to help you.
 
Associate
Joined
25 Feb 2006
Posts
194
Code:
	function setup()
	{
	
	var formfields = document.getElementsByTagName("input");
	formfields[0].addEventListener("focus",fireevent,false);
	
	}
	function fireevent()
	{
	alert(this.id);
	return false;
	}

<body onload="setup()">

Shouldnt it be gotfocus or focusgained? rather than just focus? Not sure of the exact syntax.. but you get the idea.
 
Back
Top Bottom