I have a js and htlm code in jfiddle.
I have created the button onclick event on the object method and on the page load it firing the event. Is this some problem with my code.
var user = {
data: [
{name: 'T. Woods', age: 37},
{name: 'P. Mickelson', age: 43}
],
clickHandler: function (event) {
console.log(this);
var randomNum = ((Math.random() * 2 | 0) + 1) - 1; // Random number between 0 and 1
$('input').val(this.data[randomNum].name + ' ' + this.data[randomNum].age);
}
};
console.log(user);
$('button').click(user.clickHandler(this));
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>Homepage Headline</h1>
<div id="div1">
<p>
<button>Get Random Person</button><br>
<input type="text">
</p>
</div>
<script type="text/javascript" src="oops.js"></script>
</body>
</html>