Home > Net >  HTML button onclick function not recognised in JavaScript
HTML button onclick function not recognised in JavaScript

Time:04-14

I have an HTML file linked to a script. A button defined in the HTML has an onclick function 'incrementLabel()' but the function in the script throws the warning:

'incrementLabel' is declared but its value is never read.

HTML:

<!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">

        <link rel="stylesheet" href="styles.css">
        <script src="js/Main.js"></script>

        <title>Test Web App</title>

    </head>

    <body>
        <button onclick="incrementLabel()">Test</button>
        <label id="testLabel">0</label>
    </body>

</html>

Javascript code:

function incrementLabel() {

    var text = document.getElementById("testLabel").textContent;
    document.getElementById("testLabel").innerText = (parseInt(text)   1);

}

I can't find any solutions to the problem other than writing the function in a in HTML. Any help would be much appreciated.

Thanks!

CodePudding user response:

<!DOCTYPE HTML>
<script>
function incrementLabel() {

    var text = document.getElementById("testLabel").textContent;
    document.getElementById("testLabel").innerText = (parseInt(text)   1);

}
</script>
<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">

        <link rel="stylesheet" href="styles.css">
        <script src="js/Main.js"></script>

        <title>Test Web App</title>

    </head>

    <body>
        <button onclick="incrementLabel()">Test</button>
        <label id="testLabel">0</label>
    </body>

</html>

This works perfectly fine. Check if you are importing your JS script correctly.

CodePudding user response:

  1. You can put the javascript code into a before the closing tag .

    HTML:

<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">

    <link rel="stylesheet" href="styles.css">
    <script src="js/Main.js"></script>

    <title>Test Web App</title>

</head>

<body>
    <button onclick="incrementLabel()">Test</button>
    <label id="testLabel">0</label>

<script>
    function incrementLabel() {

    var text = document.getElementById("testLabel").textContent;
    document.getElementById("testLabel").innerText = (parseInt(text)   1);

    }
</script>
</body>
  1. Some of online tools like https://playcode.io don't recognise your code but I have tested in vscode and works fine.

  2. Maybe have to use other online tool or can test if you have imported the code well with a console.log("Works fine") into your javascript file.

Sorry for my english.

  • Related