2

I have simple Javascript code for onClick event but I get

Uncaught ReferenceError: validate is not defined

HTML:

<head>
    <script src="js/confirmation.js"></script>
</head>
...
<button type="button" name="confirm" onclick="validate()">Validate</button>

JS:

function validate() {
   alert("hi");
}

Am I missing something ???

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
smile 22121
  • 285
  • 4
  • 20

2 Answers2

0

Because you're actually defining function validate on a local scope. The solution is quite obvious. Just make it global.

Define this function on global scope

function validate() {
   alert("hi");
}
console.log(this); //it must be the `window` object

Assign this function to the global variable window.

Replace

function validate() {
   alert("hi");
}

with

window.validate = function() {
   alert("hi");
}
Community
  • 1
  • 1
Lewis
  • 14,132
  • 12
  • 66
  • 87
0

Try this it will work :

use global variable window to call the function validate.

/**
*
* Validate the input.
*/
window.validate = function() {
  alert("hi");
}

Jsfiddle : https://jsfiddle.net/uf1d4aab/1/

Debug Diva
  • 26,058
  • 13
  • 70
  • 123