Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running javascript function inside jsp

Tags:

javascript

jsp

Is it possible to run javascript functions inside jsp tags? I'd like to run a sudden function as many times as there's objects in my ArrayList. Below doesen't work, but I hope it gives an idea of what I'm trying to achieve.

    <script>
    function test(){
        alert();
    }
    </scripts>


<% 
ArrayList<Marker> list = new ArrayList<Marker>();

list = (ArrayList<Marker>)request.getAttribute("markers"); 

for(int i = 0; i < list.size(); i++){
    %>
        <script>
        <%
        test();
        %>
        </script>
    <%
}
%>

Is it possible to do it with something like ?

<c:forEach var="name" items="${markers}">
   <%-- call my javascript function --%>

</c:forEach>
like image 983
JonCode Avatar asked Sep 26 '15 14:09

JonCode


People also ask

How can use JavaScript function in JSP?

As we know that javaScript is a Client-side script and JSP is a Server-side so we can attach a form validation to a JSP page to redirect HTML page and javaScript content. -Before submitting page to web server, it should be validate HTML field data. This validation can be done on client side instead directly to server.

Can we call JavaScript function from JSP?

JavaScript cannot call java method directly since it is on the server. You need a Java framework like JSP to call when a request is received from JavaScript.

How do I call a function from one JSP to another?

Including jsp into another jsp will result in execution jsp scriplets and/or other java codes of the included jsp. Ideally you should have your java script into external js and import js files using script tag in the jsp/html page. However, if you still want to go for it, try using jsp:include .

Can we use JavaScript variable in JSP?

Answers. Yes You can access JSP variable in javascript using expression tag and vice versa.


2 Answers

Below correction in your code will work fine for you

<script>
    function test(){
        alert("Hello"); // added sample text
    }
 </script>


<% 
ArrayList<Marker> list = new ArrayList<Marker>();

list = (ArrayList<Marker>)request.getAttribute("markers"); 

for(int i = 0; i < list.size(); i++){
    %>
        <script>
        test(); //No need to put java script code inside scriptlet
        </script>
    <%
}
%>
like image 84
Murli Avatar answered Oct 23 '22 03:10

Murli


<% 
ArrayList<Marker> list = new ArrayList<Marker>();

list = (ArrayList<Marker>)request.getAttribute("house"); 

for(int i = 0; i < list.size(); i++){
    %>
      <script>
         test('<%= list.get(i).name %>');
      <script>
    <%
}
%>
<script>
    function test(i){
        alert(i);
    }
</script>
like image 27
Luka Govedič Avatar answered Oct 23 '22 03:10

Luka Govedič