0

I am running some JavaScript and when I click the button the console says the function its calling is not defined. But I did define it above it. I even logged it to the console and it said its a: function () {code}.

Where's the issue?

window.onload = function() {
  var userdata = document.getElementById("username").value;
  var pwdata = document.getElementById("passwordfield").value;
  var check = function() {
    alert("hey");
  };
  console.log(check);
}
<html>
<h1>Login</h1>
<input id="username" type="text" placeholder="Username" name="username">
<input type="password" id="passwordfield" placeholder="Password" name="password">
<button onclick="check()">Log in</button>

</html>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
u32i64
  • 2,384
  • 3
  • 22
  • 36
konyv12
  • 716
  • 2
  • 8
  • 23
  • Possible duplicate of [Inline event handler not working in JSFiddle](http://stackoverflow.com/questions/5431351/inline-event-handler-not-working-in-jsfiddle) –  Mar 04 '17 at 13:17
  • Uh, not 100% sure, but you're closing your html document on line 6. And the script is defined outside of the html doc – MrKickkiller Mar 04 '17 at 13:18

1 Answers1

0

Define function outside of window.onload and it will work perfectly:

var check = function() {
  alert("hey");
};

window.onload = function() {
  var userdata = document.getElementById("username").value;
  var pwdata = document.getElementById("passwordfield").value;
  console.log(check);
}
<html>
<h1>Login</h1>
<input id="username" type="text" placeholder="Username" name="username">
<input type="password" id="passwordfield" placeholder="Password" name="password">
<button onclick="check()">Log in</button>

</html>

<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
u32i64
  • 2,384
  • 3
  • 22
  • 36