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:


$(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?

You could simply just add a global var before the events

var $val1 = false;

Believe me, I did this but it didn’t work xD Now it works lol :smiley:

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

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! :slight_smile: