SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Addict Banana Man's Avatar
    Join Date
    Dec 2005
    Posts
    389
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Setting var in jQuery function

    Hi,

    Im working with Javascript for the first time and am having a problem setting a javascript var on a jQuery onclick function. Can anyone see why the var in document.write(num_cow); is not being set?

    Thanks

    Code:
    <script>var num_cow;
    </script>
    
    <div class="green_button_1_class_1 ">ADD TO YOUR FARM</div>
    
    <script>		
    	
    			document.write(num_cow);
    	
    		</script>
    
    <script>
    $(document).ready(function() {
    
    $('.green_button_1_class_1').click(function() {
    			
    			// increment the Cow variable
    			num_cow = num_cow + 1;
    			
        		return false;
      		});
    }
    </script>

  2. #2
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    4,813
    Mentioned
    141 Post(s)
    Tagged
    0 Thread(s)
    Yes, you are writing the num_cow variable to the page on page load, at the time of page load, num_cow is undefined (your top line), it isn't truly defined until the div is clicked.

    Instead you likely want to do this
    Code JavaScript:
     <script>var num_cow = 0;</script>
     
    <div class="green_button_1_class_1 ">ADD TO YOUR FARM</div>
    <div id="itemsForFarm"></div>
     
    <script>
    $(document).ready(function() {
         $('.green_button_1_class_1').click(function() {
                // increment the Cow variable
                num_cow = num_cow + 1;
                $('#itemsForFarm').text(num_cow);
                return false;
         });
    });
    </script>
    Be sure to congratulate xMog on earning April's Member of the Month
    Go ahead and blame me, I still won't lose any sleep over it
    My Blog | My Technical Notes

  3. #3
    SitePoint Addict Banana Man's Avatar
    Join Date
    Dec 2005
    Posts
    389
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Brilliant! That's sorted it.


Bookmarks

Posting Permissions

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