Erwin Manalang
Erwin Manalang

Reputation: 347

Array compute condition

I have here a range of value with specific charge. I've use if function to fulfill the conditions but my code seems too long to complete this condition. I've search a lot and founded out that array may solve my problem but I cant run it correctly. here is my working code.

<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

<div class="collapse" id="pera-padala">
  <div class="card card-body">
        <div class="form-element">
        <span>B. Input ang amount na ipapadala  </span>
        <input name="entry.1812134286" id="padala-pera"  type="number"  required="">
      </div>
      <br>
       <div class="form-element">
              <span>C. Total Babayaran: <span id="padala-result"></span>



 $('#padala-pera').keyup(function () {
  let inputVal = $('#padala-pera').val();
  inputVal = inputVal ? inputVal : '-30';
  if (inputVal <= 1000  ) {
    $('#padala-result').text("₱".concat(Math.ceil(parseFloat(inputVal) + 30)));
  }
  else if (inputVal > 1000 && inputVal <= 1500) {
    $('#padala-result').text("₱".concat(Math.ceil(parseFloat(inputVal) + 45)));
  }
    else if (inputVal > 1500 && inputVal <= 2000) {
    $('#padala-result').text("₱".concat(Math.ceil(parseFloat(inputVal) + 60)));
  }
     else if (inputVal > 2000 && inputVal <= 2500) {
    $('#padala-result').text("₱".concat(Math.ceil(parseFloat(inputVal) + 75)));
  }
});

and here are the conditions to meet.

enter image description here

thanks

Upvotes: 1

Views: 45

Answers (1)

Kinglish
Kinglish

Reputation: 23654

Looks like there is a predictable pattern. First we convert the input into a number with the shorthand + prefix. Then we find the fee - if the amount is less than 1000 it's a fixed number, but if over 1000, it increments 15 for every 500 over, plus the original 30. We get this number from 30 + Math.ceil((iv-1000)/500) * 15

$('#padala-pera').keyup(function() {
  let iv = +$(this).val();
  let num;
  if (iv <= 1000) num = 30;
  else num = 30 + Math.ceil((iv-1000)/500) * 15
  let result = iv + num;
  $('#padala-result').text(`₱${Math.ceil(result)}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='padala-pera' />
<div id='padala-result'></div>

Upvotes: 1

Related Questions