Eido95
Eido95

Reputation: 1383

Why does HTML button doesn't invoke onclick event assigned function

When trying to invoke a JavaScript function of a .js file from .html file the function doesn't being invoked.

Project hierarchy:

Example #1 - using .html - Works

main.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Main page</title>
    </head>
    <body>
        <label id="label1"></label>
        <input id="text1" type="text"/>
        <button onclick="document.getElementById('label1').innerHTML = document.getElementById('text1').value">Button</button>
    </body>
</html>

Example #2 - using .html and .js - Doesn't work

main.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Main page</title>
    </head>
    <body>
        <label id="label1"></label>
        <input id="text1" type="text"/>
        <button onclick="outputInput()">Button</button>

        <script src="/js/script.js"></script>
    </body>
</html>

script.js

function outputInput(){
    document.getElementById('label1').innerHTML = document.getElementById('text1').value;}

Upvotes: 0

Views: 214

Answers (1)

Touffy
Touffy

Reputation: 6561

In your <script src="/js/script.js"></script>, you're using an absolute URL. Based on further testing, it appears that your "js" folder is not at the root of your website and so it is not found there. Using a relative URL src="../js/script.js" is more tolerant about where you put things.

Upvotes: 1

Related Questions