In this example I have two action :
when you add quantity of users - it will be automatically calculated by a price in the input with total sum
when you already add the quantity of users > total sum is calculated > if you click on EUR - in input with total sum, the sum will be translated to euro.
So, every thing work fine - but I don't like that the "usesQuantity" has the global scope! Any ideas how make it local and save the working version http://jsfiddle.net/gb2447jd/5/
tried something like:
$('#user-quantity').keyup(function(){
var userQuantity = parseInt($(this).val());
if( userQuantity >=1 && userQuantity <=200){
valid(userQuantity);
} else {
$('#total-sum').val("error");
}
});
$('#usd').on('click', function(){
$('#eur').removeClass('greenChacked');
$(this).addClass('greenChacked');
valid(userQuantity);
});
$('#eur').on('click', function(){
$('#usd').removeClass('greenChacked');
$(this).addClass('greenChacked');
valid(userQuantity);
});
$('#usd').trigger('click');
function valid(userQuantity){
if( $('#usd').hasClass('greenChacked') ){
var usdCurr = userQuantity * 10 + 'doll';
$('#total-sum').val(usdCurr);
}
if( $('#eur').hasClass('greenChacked') ){
var eurCurr = userQuantity * 5 + 'eur';
$('#total-sum').val(eurCurr);
}
}
Define your variable (userQuantity) within the function. It will be available via closure to the other functions and callbacks without having global scope. See this new jsFiddle .
The start of the new code looks as follows:
$(document).ready(function () {
var userQuantity;
$('#user-quantity').keyup(function () {
userQuantity = parseInt($(this).val());
if (userQuantity >= 1 && userQuantity <= 200) {
setCurrency();
} else {
$('#total-sum').val("error");
}
});
You could wrap your code inside a immediately invoked function
(function () {
var userQuantity;
$(document).ready(function () {
//rest of your code
};
}());
More info here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.