0

I have a select menu with various option values. I need to multiply the selected value by "10" if the value selected is less than 25, if the value selected is 25 or greater I need it to multiply by "12".

I am new to JS. I am able to get it to work by multiplying by just 10 using the code below, but I do not know how to write the if/else statement to check if the selection is less than 25 and multiply by 10 or 25 or greater and multiply by 12.

Html:

<table width="100%" border="0">
  <tr>
    <td>
      <select id="licenseRegs">
        <option value="5">5</option>
        <option value="10">10</option>
        <option value="15">15</option>
        <option value="20">20</option>
        <option value="25">25</option>
        <option value="50">50</option>
        <option value="75">75</option>
        <option value="100">100</option>
        <option value="125">125</option>
      </select>
      </td>

      <td id="total-price">Price show here</td>
    </tr>
  </table>

Javascript: This multiplies all select values by 10. I need it to multiply by 10 if less than 25 but multiply by 12 if 25 or more.

// calculate price of # of computer selection
$(document).ready(function() {
  var pricePerReg = 10;
  var licenseRegsSelect = $('#licenseRegs');

  function updateTotalPrice() {
    licenseRegs = licenseRegsSelect.val();
    $('#price').html(pricePerReg * licenseRegs);
  }

  licenseRegsSelect.change(function() {
    updateTotalPrice();
  });

  updateTotalPrice();
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rex
  • 223
  • 2
  • 5
  • 22

1 Answers1

1

Using your code, I've added an if/else statement (hopefully it's self-explanatory given your description of the problem. it does just that - check whether licenseRegs is smaller than, or either bigger than or equal to 25.).

I've also used the built-in parseInt() to fetch the number as an integer; it is stored as a string. (this is the difference between "25" (string) and 25 (int). this might not be necessary but it's good practice. refer to this question for more information: How do I convert a string into an integer in JavaScript?

// calculate price of # of computer selection
$(document).ready(function() {
  var pricePerRegUnder = 10;
  var pricePerRegAbove = 12;
  var licenseRegsSelect = $('#licenseRegs');

  function updateTotalPrice() {

    licenseRegs = parseInt(licenseRegsSelect.val(), 10);

    ///////////// New code here ////////////
    var total;
    if (licenseRegs < 25) {
      total = licenseRegs * pricePerRegUnder;
    } else {
      total = licenseRegs * pricePerRegAbove;
    }
    //////////// Ends here /////////////////

    $('#price').html(total);
  }

  licenseRegsSelect.change(function() {
    updateTotalPrice();
  });

  updateTotalPrice();
});
Community
  • 1
  • 1
nadavvadan
  • 3,930
  • 1
  • 17
  • 29