Steve B
Steve B

Reputation: 33

Calculating unit price based on quantity entered

I'm trying to create a script that displays a price in one box based on the number of employees entered in an adjacent box. The script works fine for a static amount, i.e. the base price is £8 per employee. If 5 is entered the price displayed is correct, £40.

The problem I'm having is changing the unit price when a certain threshold is met. The unit price for 1-5 employees is 8, 6-21 is 7 and 22-50 is 6. No matter what is entered in the employee box, the number is always multiplied by 8.

I'm very inexperienced when it comes to javascript so any help will be very welcome!

Here is my code:

<div class="employee-button">
    <form name="calculator" id="calculator">
    <input name="employees" id="employees" type="text" placeholder="# of Employees" />
    </form>
</div>  
<div class="cost-button">
    <span id="result">Monthly Cost</span>
</div>

Javascript

$(function() {

    var ccNum;
    $('#employees').keyup(function(){
        ccNum = $(this).val();
    });

    if((ccNum >= 0) && (ccNum <= 5)){
         var unitPrice = 8
    }
    else if((ccNum >= 6) && (ccNum <= 21)){
         var unitPrice = 7
    }
    else if((ccNum >= 21) && (ccNum <= 50)){
         var unitPrice = 6
    }
    else var unitPrice = 8;

    $('#employees').keyup(function(){
        $('#result').text(ccNum * unitPrice);
    });

})

Upvotes: 2

Views: 1270

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

In addition to putting the code inside your event handler, you do not need to keep declaring the same variable over and over. Also the test for 0 to 5 is not needed (as already covered by the default value):

$('#employees').keyup(function(){
  var ccNum = ~~$(this).val();

  // Start with the default
  var unitPrice = 8;

  if((ccNum >= 6) && (ccNum <= 21)){
      unitPrice = 7;
  }
  else if((ccNum >= 21) && (ccNum <= 50)){
      unitPrice = 6;
  }
  $('#result').text(ccNum * unitPrice);
});

Note: ~~ is a shortcut conversion to an integer value.

Upvotes: 0

wvdz
wvdz

Reputation: 16641

Put everything within the keyup function. Your code wasn't working because the logic to calculate the price is only executed once, not for every keyup event.

$('#employees').keyup(function(){
  var ccNum = $(this).val();

  if((ccNum >= 0) && (ccNum <= 5)){
                var unitPrice = 8
            }
  else if((ccNum >= 6) && (ccNum <= 21)){
                var unitPrice = 7
             }
  else if((ccNum >= 21) && (ccNum <= 50)){
                var unitPrice = 6
             }
  else var unitPrice = 8;

  $('#result').text(ccNum * unitPrice);
});

Upvotes: 1

Related Questions