Dil.
Dil.

Reputation: 2076

How to set value to label in jsp page through jquery

This is my label.

<label class="control-label " for="no1" id="lbl_count">0</label>
     <button type="submit" class="btn btn-primary" id="submit_btn">Add to cart</button>

And this is the function I try to set amount of raw in the jsp page to a label. But it is not working. Both label and button not are in same div. But both of them are in same form.

   <script>
        $('document').ready(function() {
            $('#submit_btn').click(function() {

                var x = document.getElementById("mytable").rows.length;
                alert(x);
                //    $("label[for='no1']").text(x);
               //     $("#lbl_count").text(x);
            });
        });
    </script>


I tried several ways non of them are working.. Alert is working. That means data is coming. So how to fix this. Please help me. Thank you.

Upvotes: 0

Views: 5818

Answers (1)

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

In this case, you can't see the changes of label because right after submit button was clicked, the page refresh(showing the original state). Try prevent the default event for the element, so then you can see the changes on label.

<script>
    $('document').ready(function() {
        $('#submit_btn').click(function(e) {
            e.preventDefault(); //<-add ^this
            var x = document.getElementById("mytable").rows.length;  // use this or try with static value like var x = "23";
            $("#lbl_count").text(x);
        });
    });
</script>

But, the form will not submit. As you mention before, having record to save, then use ajax post instead.

AJAX EXAMPLE

HTML

<form action="">
  <label for="no1" id="lbl_count">0</label>
  <input type="text" name="var1" id="var1"/>
  <button type="submit" id="submit_btn">Add to cart</button>
</form>

JS

  $('document').ready(function() {
        $('#submit_btn').click(function(e) {
            e.preventDefault();               
            $.ajax({
                type : 'post',
                data : 'var1='+$('#var1').val(),
                url : 'your_jsp_process_page.jsp',
                success : function(data){
                    var x = 'hello';
                    $("#lbl_count").text(x);
                }
            });

        });
    });

your_jsp_process_page.jsp In this page, need to retrieve the value sent from ajax. In this example, retrieve it with name var1. Here you can see the data key and value paired data : 'var1='+$('#var1').val(),.

Upvotes: 1

Related Questions