Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access javascript variable value in jsp

I want to pass a javascript variable to my servlet, where I need to use it.

In javascript, the variable count returns the rows of my table and I can show count in the jsp, using $('#counter').html(count); , but I cannot pass count's value to my servlet. I tried document.getElementById("hiddenField").value=count; but it doesn't work.

Javascript

<script>
    var count = 3;
    $(function() {
        $('#counter').html(count);
        $('#addButton').bind('click', function() {
             count = document.getElementById("dataTable").getElementsByTagName("tr").length;
            $('#counter').html(count);
        });
        $('#deleteButton').bind('click', function() {
            count = document.getElementById("dataTable").getElementsByTagName("tr").length;
            $('#counter').html(count);
        });
    });
    document.getElementById("hiddenField").value=count; // ???
</script>

JSP

Count: <span id="counter"></span> <%-- it works --%>

<form method="post" action="newteamsubmit"> 
...
<input type="hidden" id="hiddenField" name ="countRows" />
<input type="submit" name ="button1" value=" Submit " />
<input type="submit" name = "button1" value=" Cancel " />
</form>

Servlet

String cr = request.getParameter("countRows"); //I' ve tried also to convert it 
// to int, but that's not my problem, since I cannot pass the value as a start

I've spent many hours, trying to figure out how I can access a javascript variable in jsp, but I haven't found any solution. Thanks in advance.

like image 239
D-Lef Avatar asked Jul 11 '26 18:07

D-Lef


1 Answers

The count is computed each time the add button or the delete button are clicked. But you only set the hidden field value once, when the page is loaded (and its value is thus hard-coded to 3).

You must set it, as you're doing for the #counter element, in your click handlers:

$('#addButton').bind('click', function() {
    count = document.getElementById("dataTable").getElementsByTagName("tr").length;
    $('#counter').html(count);
    $('#hiddenField').val(count);
});
$('#deleteButton').bind('click', function() {
    count = document.getElementById("dataTable").getElementsByTagName("tr").length;
    $('#counter').html(count);
    $('#hiddenField').val(count);
});

Also note that you're repeating exactly the same code in two click handlers here. You should do that only once, for the two buttons:

$('#addButton, #deleteButton').bind('click', function() {
    count = document.getElementById("dataTable").getElementsByTagName("tr").length;
    $('#counter').html(count);
    $('#hiddenField').val(count);
});

or even, since you're using jQuery:

$('#addButton, #deleteButton').bind('click', function() {
    count = $("#dataTable tr").length;
    $('#counter').html(count);
    $('#hiddenField').val(count);
});
like image 160
JB Nizet Avatar answered Jul 13 '26 08:07

JB Nizet