0

Let's say I have an input button.

<input type="button" value="click here />

Then there's other HTML and Java codes.

.
.
.
.
.

Then there's a div tag.

<div>

</div>

and inside this div I want to execute these codes, but Only when I click on that button.

<% `int i = 0;
while(i<3) {
%> <div> I love you </div>
<% i++;} %>`
Ali Bassam
  • 9,691
  • 23
  • 67
  • 117
  • 1
    http://stackoverflow.com/questions/10489132/run-script-only-on-button-click-in-jsp – CloudyMarble Aug 01 '12 at 09:06
  • When you click on that button, it is already too late for JSP to do anything about it. You may have to throw client-side scripting (i.e. JavaScript) into the mix, too. – Thilo Aug 01 '12 at 09:07
  • possible duplicate of [How to call a java method from a jsp when a html element is clicked?](http://stackoverflow.com/questions/516267/how-to-call-a-java-method-from-a-jsp-when-a-html-element-is-clicked) – Thilo Aug 01 '12 at 09:08

3 Answers3

2

Java code is executed on the server. Events like clicks happen on the user's browser. So a click cannot call java code directly.

You need to:

  • either code the filling of the div in pure javascript,
  • or make an ajax call when the button is clicked, to retrieve the content of the div from the server.
kgautron
  • 7,915
  • 9
  • 39
  • 60
0

Probably Onclick event you can set the value of a hidden parameter and in div check for parameter value in script-let using if else but again java code will be executed on server and hence it will be new request to same Action otherwise use Ajax to populate data in div from sever.

amicngh
  • 7,831
  • 3
  • 35
  • 54
0

you need to use ajax and servlet to acheive this. servlet would send the code in response. The success part of ajax would add the returned string to the div. You would need to assign an id to div. The ajax syntax would be

$.ajax({
    url:"../servletname",
    type:"POST",
    data:{},
    success:function(response){
        $("#divid").html(response);

    }
});

You need to call the servlet in the jsp using onClick function.

dr_mak
  • 62
  • 9