I have four form fields that should be autocompleted based on the input of the user, in the following way: when the first field is filled in, the second field should be filled with the first one's value * 2. When the 3rd field is filled, the fourth one should be filled with this third value * the first one.

I have no problems with the first two fields, but the third and fourth one keep returning 0 as a result.

Code:
$(function() {
	
	var $val1 = 0;
	var $val2 = 0;
	
	$('input[name="first"]').keyup(function() {
		$val1=parseInt($(this).val());
		$('input[name="second"]').val($val1*2);
	}),
	
	$('input[name="third"]').keyup(function() {
		$val2 = parseInt($(this).val());
		$('input[name="fourth"]').val($val2*$val1);
	})
})