Tony33
Tony33

Reputation: 147

JavaScript function does not work when used inside onclick attribute

I have a simple html link, in which I call a JavaScript function onClick and try to switch the value taken in. It's not working.

Here is my code:

function lang(language) {
  switch (language) {
    case "it-IT":
      alert("Italiano selezionato");
      break;
    case "en-US":
      alert("English selected");
      break;
  }
}
<p><a href="#" onClick="lang('en-US');">English</a></p>
<p><a href="#" onClick="lang('it-IT');">Italiano</a></p>

Upvotes: 5

Views: 139

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272106

When you assign JavaScript code to the onclick handler, it is executed in a special scope where the properties of the element are available directly as is it were running inside a with (element) { } block.

In your example, the lang variable corresponds to the lang attribute of the element. Other examples that will cause the same error include id, title, style and href. Think of it as executing the following code:

function lang() {
}

with(element) {
    lang("en-US");
    // type error since lang resolves to element.lang
    // instead of the outer lang
}

You can simply namespace your function:

var MyFancyFunctions {
    lang: function {
    }
};
<a onclick="MyFancyFunctions.lang('en-US')">English</a>

Or just remove the ambiguity:

<a onclick="window.lang('en-US')">English</a>

References:

The internal raw uncompiled handler

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68655

The problem is here. Around the onclick event handler there is used with, which allow you to use all global attributes (including lang) there. So it tries to access the global lang property.

So change you function name to anything else, but no attributes names

<p><a href="#" onClick="alertLang('en-US');">English</a></p>
<p><a href="#" onClick="alertLang('it-IT');">Italiano</a></p>

<script>
  function alertLang(language) {
  switch (language) {
    case "it-IT":
      alert("Italiano selezionato");
      break;
    case "en-US":
      alert("English selected");
      break;
  }
}
  </script>

But it will work if you add it as a event handler in Javascript

<p><a href="#">English</a></p>

<script>
  function lang() {
      alert("English selected");
  }
  
  document.querySelector('p').onclick = lang;
  </script>

Upvotes: 3

j08691
j08691

Reputation: 207901

Don't use lang for your function name, the browser is using it already.

function xlang(language) {
  switch (language) {
    case "it-IT":
      alert("Italiano selezionato");
      break;
    case "en-US":
      alert("English selected");
      break;
  }
}
<p><a href="#" onClick="xlang('en-US');">English</a></p>
<p><a href="#" onClick="xlang('it-IT');">Italiano</a></p>

Upvotes: 12

Related Questions