SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Thread: Variable scope

  1. #1
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Variable scope

    Is it possible, from inside a function, to access a variable that is inside another function?

    Specifically, what I'm doing here is that when a user enters a value in the text field "one", the doubled value is inserted into text field "two". I would like to take the value that was entered in the first text field and use it to calculate something in another text field. Here's the code:

    Code:
    $(function() {
    	
    	$('input[name="one"]').keyup(function() {
    		$val1=parseInt($(this).val());
    		$('input[name="two"]').val($val*2);
    	}),
    	
    	$('input[name="three"]').keyup(function() {
    		$val=parseInt($(this).val());
    		$('input[name="four"]').val($val*$val1);
    	})
    	
    })
    I would like to use $val1 final value in the second function. Is this possible?

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    You could simply just add a global var before the events

    Code JavaScript:
    var $val1 = false;

  3. #3
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SgtLegend View Post
    You could simply just add a global var before the events

    Code JavaScript:
    var $val1 = false;
    Believe me, I did this but it didn't work xD Now it works lol

    Anyways, just out of curiosity, is this the only way to access the variable or are there other ways?

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,198
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    From my memory this is the only way i know of storing variables within the jQuery DOM ready function for the local internal scope.

  5. #5
    SitePoint Addict D3V4's Avatar
    Join Date
    May 2010
    Posts
    370
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SgtLegend View Post
    From my memory this is the only way i know of storing variables within the jQuery DOM ready function for the local internal scope.
    Ok, thanks!


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
  •