www.webdeveloper.com
Results 1 to 2 of 2

Thread: jQuery Variable Addition

  1. #1
    Join Date
    Nov 2011
    Posts
    1

    jQuery Variable Addition

    Hi,

    I have javascript which counts seperately every time 2 seperate buttons are clicked, this then outputs the amount on the same page. This works, however I am now trying to add a third value to output on the page which is the total of the clicks which i would calculate by adding the 2 attributes together. This just doesn't seem to be working though.

    java
    Code:
    <script type="text/javascript">
    var NextClick = 0;
    var PrevClick = 0;
    var TotalClicks = 0;
    
    function getValueNext()
    **{
      var y=document.getElementById("NextClick").value = ++NextClick
      $('.NextClick').val(y);
    **}
    
    function getValuePrev()
    **{
      var x=document.getElementById("PrevClick").value = ++PrevClick
      $('.PrevClick').val(x);
    **}
    
    function getSumClicks()
      {
      var z= x + y
      $('.TotalClicks').val(z);
      }
    
    </script>
    Html
    Code:
      Clicked next <input class="NextClick" size="3" onfocus="this.blur();" value="0"> times.
      Clicked prev <input class="PrevClick" size="3" onfocus="this.blur();" value="0"> times.
      Clicked total <input class="TotalClicks" size="3" onfocus="this.blur();" value="0"> times.

  2. #2
    Join Date
    Dec 2008
    Posts
    488
    Well, since you created "x" and "y" inside your getValueNext() and getValuePrev() functions, the variables do not exist outside of those functions. Their scope is local. You'll need to give them a global scope in order for another function to access them. Or you could simply add a global sum variable and add to it each time you add to "x" and "y". I see you've already created some global variables, so why not use those?:

    Code:
    <script type="text/javascript">
    var nextClick = 0, prevClick = 0, totalClick = 0;
    
    function getValueNext() {
        ++nextClick;
        ++totalClick;
        $('.NextClick').val(nextClick);
    }
    
    function getValuePrev() {
        ++prevClick;
        ++totalClick;
        $('.PrevClick').val(prevClick);
    }
    
    function getSumClicks() {
        $('.TotalClicks').val(totalClick);
    }
    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles