0

In this example I have two action :

  1. when you add quantity of users - it will be automatically calculated by a price in the input with total sum

  2. 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);
    }
  }
Mongo
  • 151
  • 7

2 Answers2

1

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");
        }
    });
Kolban
  • 13,794
  • 3
  • 38
  • 60
1

You could wrap your code inside a immediately invoked function

(function () {
    var userQuantity;

    $(document).ready(function () {
        //rest of your code 
    };
}());

More info here.

Community
  • 1
  • 1
Bruno Calza
  • 2,732
  • 2
  • 23
  • 25