Mongo
Mongo

Reputation: 151

remove var from global scope

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);
    }
  }

Upvotes: 0

Views: 46

Answers (2)

Bruno Calza
Bruno Calza

Reputation: 2780

You could wrap your code inside a immediately invoked function

(function () {
    var userQuantity;

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

More info here.

Upvotes: 1

Kolban
Kolban

Reputation: 15256

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");
        }
    });

Upvotes: 1

Related Questions