Leo Caracciolo Leo Caracciolo - 2 years ago 95
Javascript Question

Why the name of a function can not be equal to the id of an input in javascript

Example with function name equal to the value of the input id

function idade(){

var idade = document.getElementById('idade').value;


<form name="myForm">

Age: <input type="text" name="idade" id="idade" /></br></br>

<input type="submit" onclick="idade()" />


Answer Source

It can, but in that context it's being shadowed by the automatic variable created for the input element within the form.

The environment in which onxyz-attribute-style event handlers run is effectively a series of with statements dumping all kinds of identifers (technically, bindings) into the scope where they run, like this:

with (document) {
    with (form) {
        with (theInput) {

The form has a property on it named idade because the input has that name. So in the context where idade() is above, idade refers to that form element, not your global function.

This is one of the many reasons not to use onxyz-attribute-style event handlers. (Another is that they can only call functions dumped into their scope like that or global functions, and globals are best avoided.)

Instead, use modern event handling via addEventListener (attachEvent on old IE). My answer here provides a cross-browser hookEvent function you can use if you need to support old IE.

Here's your example with addEventListener and making your function non-global:

// Scoping function so we don't create globals
(function() {
  function idade(e) {

    var idade = document.getElementById('idade').value;

  document.querySelector("input[type=submit]").addEventListener("click", idade);

<form name="myForm">
  Age: <input type="text" name="idade" id="idade">
  <input type="submit">

A few other things I fixed in that:

  1. </br> is not a valid HTML tag. It's just <br> (or <br /> if you're using XHTML, but if you were using XHTML, you would know that).

  2. input elements are void elements, there's no need for a / before the > on them (it's allowed but ignored). Again, you're not using XHTML.

  3. Your input has no id, so getElementById will not find it. It has a name. (you've added it now)

Also, in the above I had idade cancel the form submission, just so the form stays there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download