Reputation:
I'm trying to get var with name rate_value
outside #rate_country
. So in #ch_rate
function this var should have the same value.
How I can do it?
<script>
var rate_default = 50;
var rate_value = ''; // this doesn't work
$('#rate_country').change(function(){
var rate_input = $('#ch_rate').val();
var rate_country = $(this).val();
if (rate_country == 'AD') {
var rate_value = rate_default * 2;
if (rate_value > rate_input) {
$('#rate_validity').addClass('validity_w');
$('#ch_rate').addClass('i_wrong')
} else {
$('#rate_validity').removeClass('validity_w');
$('#ch_rate').removeClass('i_wrong')
}
} else if (rate_country == 'AG') {
var rate_value = rate_default * 5;
}
});
// so the rate_value should be 250 if rate_country == AG or 100 if rate_country == AD
$('#ch_rate').keyup(function(){
let $this = $(this);
var rate_input = $(this).val();
var rate_regexp = /^((0|[1-9]\d*)(\.\d+)?)?$/;
if (rate_value > rate_input || !rate_regexp.test(rate_input)) {
$('#rate_validity').addClass('validity_w');
$('#ch_rate').addClass('i_wrong')
} else {
$('#rate_validity').removeClass('validity_w');
$('#ch_rate').removeClass('i_wrong')
}
});
</script>
Upvotes: 0
Views: 53
Reputation: 15365
Declare rate_value once globally with var rate_value
then refer to it as rate_value
. If you use var rate_value
again it will override.
var rate_default = 50;
var rate_value = ''; // Define rate_value once here
$('#rate_country').change(function(){
var rate_input = $('#ch_rate').val();
var rate_country = $(this).val();
if (rate_country == 'AD') {
rate_value = rate_default * 2; //DO NOT USE var here, just change the value of rate_value
if (rate_value > rate_input) {
$('#rate_validity').addClass('validity_w');
$('#ch_rate').addClass('i_wrong')
} else {
$('#rate_validity').removeClass('validity_w');
$('#ch_rate').removeClass('i_wrong')
}
} else if (rate_country == 'AG') {
rate_value = rate_default * 5; //DO NOT USE var here, just change the value of rate_value
}
console.log("rate_value is now: " + rate_value); //See what rate_value is now
});
// so the rate_value should be rate_default * 5 if rate_country == AG
$('#ch_rate').keyup(function(){
console.log("rate_value is now: " + rate_value); //See what rate_value is now
let $this = $(this);
var rate_input = $(this).val();
var rate_regexp = /^((0|[1-9]\d*)(\.\d+)?)?$/;
if (rate_value > rate_input || !rate_regexp.test(rate_input)) {
$('#rate_validity').addClass('validity_w');
$('#ch_rate').addClass('i_wrong')
} else {
$('#rate_validity').removeClass('validity_w');
$('#ch_rate').removeClass('i_wrong')
}
});
Remember, var
defines the variable and sets the initial value. Every time you use var it resets the value so only use var
once (unless you really want to reset.)
Upvotes: 1
Reputation: 261
you can use a global variable or used hidden param and after you can fetch another function
Upvotes: 0