0

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?

3
  • 1
    JSP is server-side. JavaScript is client-side. The two don't mix; what you're doing is incrementing it once. Commented May 28, 2012 at 23:57
  • 1
    JSP produces HTML which get sent from webserver to webbrowser. JS is part of HTML. Rightclick page in browser and View Source to get enlightenend. Commented May 29, 2012 at 0:02
  • BalusC, I'm aware that pages are made up of HTML. Thanks, though. Commented May 29, 2012 at 0:06

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

For what I'm doing a cookie might suffice. Thanks for the idea.
0

@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...

2 Comments

Nice idea, I ended up using a cookie but this is an interesting trick and would have probably also worked.
offcourse you can do with cookies also, but for this small requirement cookies methodology will be too lengthy...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.