Home > other >  Javascript not being able to find function
Javascript not being able to find function

Time:09-28

My HTML:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Assignment A</title>
</head>
<body>
    <h1>Fortune cookies!</h1>
    <input type="text" id="input" placeholder="Add a fortune" />
    <button onclick="cookie.add()">Add a fortune!</button><br />
    <button onclick="cookie.fortune()">What does your fortune hold?</button>
    <p id="output"></p>
    <script src="3a.js"></script>
</body>
</html>

My javascript:

class Cookie
{
    constructor()
    {
        this.fortunes = ["Insert meaningful quote here.", "insert meaningless quote here."];
    }
    add()
    {
        this.fortunes.push(document.getElementById("input").value);
        document.getElementById("output").innerHTML = "fortune added!";
    }
    fortune()
    {
        document.getElementById("output").innerHTML = this.fortunes[Math.random(--this.fortunes.length)];
    }
}
var cookie = new Cookie();

I feel like I am completely blind, but for some reason whenever I click a any of the 2 buttons I made, I get the following:

53a.html:12 Uncaught TypeError: cookie.fortune is not a function
    at HTMLButtonElement.onclick (3a.html:12)

Please, help. I do not understand why my JS is unable to call this function. I must've missed something tiny but I am completely stuck in tunnel vision.

CodePudding user response:

Try to rename cookie variable to another name. It looks like conflict to document.cookie.

var cookie = new Cookie(); -> var cookieObj = new Cookie();

onclick="cookie.add()" -> onclick="cookieObj.add()"

onclick="cookie.fortune()" -> onclick="cookieObj.fortune()"

class Cookie
{
    constructor()
    {
        this.fortunes = ["Insert meaningful quote here.", "insert meaningless quote here."];
    }
    add()
    {
        this.fortunes.push(document.getElementById("input").value);
        document.getElementById("output").innerHTML = "fortune added!";
    }
    fortune()
    {
    console.log('fortune');
        document.getElementById("output").innerHTML = this.fortunes[Math.random(--this.fortunes.length)];
    }
}
var cookieObj = new Cookie();
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Assignment A</title>
</head>
<body>
    <h1>Fortune cookies!</h1>
    <input type="text" id="input" placeholder="Add a fortune" />
    <button onclick="cookieObj.add()">Add a fortune!</button><br />
    <button onclick="cookieObj.fortune()">What does your fortune hold?</button>
    <p id="output"></p>
    <script src="3a.js"></script>
</body>
</html>

CodePudding user response:

I guess Cookie is one of the names that are conflicting with names that exist in the general context. Give it a more individual name like "FortuneCookie" and it should work.

  • Related