Home > other >  Javascript ""Function not found"
Javascript ""Function not found"

Time:12-11

I have a very simple HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test 2 V2</title>
</head>
<body>
    <p>
        <label id="wordCat"></label>
        <input type="text" id="txtCat">
        <input type="button" id="btnCat" value="Load Word" onclick="fetchData(document.getElementById('txtCat').value)">
    </p> 
    <p>
        <label>Your Guess Word is:</label>
        <label id="hiddenWord"></label>
    </p>
    <script src="scripts/app.js"></script>
</body>
</html>

On clicking the button it should call the function:

async function fetchData(req) {
    console.log(req.value)
    let response = await fetch(req);
    var selectBox, option, prop;

    

    selectBox = document.getElementById("drivers");

    if (response.statusText == "OK") {
        return await response.json();      
    }else{
        throw new Error(response.statusText);
    }
}

The problem is that when I click the button it says: GET http://127.0.0.1:5500/{input value in the text box} 404 (Not Found)

Anyone can help me fixing this? This method is supposed to load all the keys present in json file and print them.

words.json

{
    "sports":       ["golf", "hockey", "football"],
    "animals":      ["giraffe", "snake", "lizard", "puma"],
    "video games":  ["pacman", "asteroids", "super mario brothers", "donkey kong"]
}

I need to print the keys in alphabetical order on HTML page.

Thanks.

CodePudding user response:

Try to attach the click event listener to the button in the script page.

document.getElementById('btnCat').addEventListener('click', ()=>{
    const value = document.getElementById('txtCat').value;
    fetchData(value);
});

CodePudding user response:

You need to put the script tag on the after the html tag and before the head tag. In your case the file with the function isn't loaded properly.

  • Related