Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call JS function within .js file into .jsp file?

Tags:

javascript

jsp

I am trying to call a javaScript function that's in .../js/index.js file to .../index.jsp file.

Any suggestion would be helpful.

Here is code within both file:

index.js

function testing() {

    if ("c" + "a" + "t" === "cat") {
        document.writeln("Same");
    } else {
        document.writeln("Not same");
    };
};

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>

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

       <!-- I want to call testing(); function here -->

    </script>
</body>
</html>
like image 996
Simple-Solution Avatar asked Jul 07 '12 15:07

Simple-Solution


1 Answers

First reference the external index.js file and then call the function in an inline script element:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
       testing();
    </script>
</body>
</html>

By the way you have an error in your test.js function. You shouldn't put a ; after if/else conditions, neither at the end of your function declaration. The correct syntax is:

function testing() {
    if ("c" + "a" + "t" === "cat") {
        document.writeln("Same");
    } else {
        document.writeln("Not same");
    }
}

or:

var testing = function() {
    if ("c" + "a" + "t" === "cat") {
        document.writeln("Same");
    } else {
        document.writeln("Not same");
    }
};
like image 156
Darin Dimitrov Avatar answered Sep 21 '22 09:09

Darin Dimitrov