Aaron
Aaron

Reputation: 1743

Updating jsp variable inside of javascript

I have a variable defined at the top of my jsp page:

<%! int count = 0; %>

I then call jquery with a buttonclick like so:

<script type="text/javascript">
$(document).ready(function() {         
    $('#somebutton').click(function() {
        var c = '<%=count%>';
        <% count += 5; %>
    });
});
</script>

The idea is that the variable count will be updated (and persist) after the function is done. However, it seems to update count locally but doesn't persist globally. When I click the button count always gets set to 5 but never increments to 10, 15, etc. upon further button clicks.

How can I update the jsp variable from within the jquery function and have it persist?

Upvotes: 0

Views: 4125

Answers (2)

Ars
Ars

Reputation: 282

@Aaron-You can use one method in javascript like

function increment(){
                var value1=document.getElementById("lbl1").value;
                value1=parseInt(value1)+5;
                document.getElementById("lbl1").innerText=value1;
            }

where lbl1 is the id of the textbox in your jsp which has the initialized value as 0 i.e. <input type="text" value="<%=count%>" id="lbl1"/>. and on button click call increment() method like this <input type="submit" onclick="increment()"/>.

Hope this meets your requirements...

Upvotes: 0

SeanJA
SeanJA

Reputation: 10354

You would have to do a call back to the server and store the data in a session variable (or cookie I suppose depending on the security needs).

Upvotes: 1

Related Questions