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>
The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.
It's a new paradigm called "Unobtrusive JavaScript". The current "web standard" says to separate functionality and presentation. It's not really a "bad practice", it's just that most new standards want you to use event listeners instead of in-lining JavaScript.
Greetings! Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.
It is safe to click on that link with # href; the page does leave/reload url. Follow the above advice with caution, as HTML5 rules explicitly state that href="#" is supposed to navigate to the top of the page. You can simply add the href attibute without content, and get the click behaviour.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With