Jnanathan February 2016

Javascript file will not load

I have a simple script that works when included in the html body. However, when running this from a relative path, and including the

<script type="text/javascript" src="simple.js"></script>

in either the header or bottom of the html file, the script will no longer run.

Can anyone point as to what I am missing ?

Thank you.

Script simple.js:

<script>
        function firstFunction(){

            var a = document.getElementById("firstInput").value;

            if(! a){
                alert("minimum input of 1 char required");
            }else{
                document.getElementById("firstOutput").innerHTML=a;
            }


        }

        function secondFunction(){
            var b = document.getElementById("secondInput").value;

            if(!b){
                alert("minimum input of 1 char required");
            }


            document.getElementById("secondOutput").innerHTML=b;
            //document.getElementById("secondOutput").innerHTML = "updated!";
        }

Answers


mmm February 2016

You only need the <script> tag if you include the javascript into your html file.

In a .js file, it's a syntax error. Just write your javascript code without the tag!

File simple.js:

function firstFunction(){

        var a = document.getElementById("firstInput").value;

        if(!a){
            alert("minimum input of 1 char required");
        }else{
            document.getElementById("firstOutput").innerHTML=a;
        }


    }

    function secondFunction(){
        var b = document.getElementById("secondInput").value;

        if(!b){
            alert("minimum input of 1 char required");
        }


        document.getElementById("secondOutput").innerHTML=b;
        //document.getElementById("secondOutput").innerHTML = "updated!";
    }

As your file is right now, make sure to place the script right before the closing body tag

<script type="text/javascript" src="simple.js"></script>
</body>

so that the elements can be found when the script is running.

Post Status

Asked in February 2016
Viewed 1,778 times
Voted 12
Answered 1 times

Search




Leave an answer