JavaScript: don't give event handler the same name as a field! 

Joined:
02/21/2009
Posts:
158

March 16, 2010 16:55:51    Last update: March 16, 2010 19:29:28
I had this seemingly innocent code that did not work:
<html>
<body>
	<script language="JavaScript" type="text/javascript">
		function sameAsInputName() {
			alert('This does not fire!');
		}
	</script>
	<form>
		<!-- onclick handler can't have the same name as field name -->
		Click the radio buttons:
		<input type="radio" value="Y" name="sameAsInputName" onclick="sameAsInputName();">Yes
		<input type="radio" value="N" name="sameAsInputName" onclick="sameAsInputName();">No
	<form>
</body>
</html>


I fired up the Chrome JavaScript console and it told me that:

Uncaught TypeError: object is not a function.

When the name sameAsInputName appeared in the inline event handler, the browser thinks that it refers to the input field(s), not the JavaScript function!

It works as expected if you attach the event handler later:
<html>
<body>
	<script language="JavaScript" type="text/javascript">
		function sameAsInputName() {
			alert('This does not fire!');
		}
	</script>
	<form>
		<!-- onclick handler can't have the same name as field name -->
		Click the radio buttons:
		<input type="radio" value="Y" name="sameAsInputName">Yes
		<input type="radio" value="N" name="sameAsInputName">No
	<form>

	<script type="text/javascript">
	    for (var i = 0; i < document.forms[0].length; i++) {
			document.forms[0].elements[i].onclick = sameAsInputName;
		}
	</script>
</body>
</html>
Share |
| Comment  | Tags
1 comment