user6570896 user6570896 - 5 months ago 22
jQuery Question

jQuery auto populate input field based on value from other input field

I'm creating a loan calculator. I was trying to figure out how to auto-populate an interest rate field based loan amount entered.

Here's a sample scenario:


  • Amount 0 - 100,000, interest rate = 4.50

  • Amount 100,001 - 500,000, interest rate = 4.4

  • Amount 500,001 - 1,000,000, interest rate = 4.3

  • Amount > 1,000,001, interest rate = 4.0



Here's my markup:

<input type="text" size="12" id="loanamount" name="loanamount"/>
<input type="text" size="2" name="tenure" />
<input type="text" size="4" id="interestrate" name="interestrate" disabled/>


Hope somebody can help me up.

Thanks.

FD

Answer

Listen for the keyup, calculate the rate, then set the value of the interest rate input:

 $("#loanamount").keyup(
   function (e) {
      var loan = $(e.currentTarget).val();
      if (loan <= 100000) {
        $('#interestrate').val('4.5');
      } else if (loan <= 500000) {
        $('#interestrate').val('4.4');
      } else if (loan <= 1000000) {
        $('#interestrate').val('4.3');
      } else if (loan >= 1000001) {
        $('#interestrate').val('4.0');
      } else {
        $('#interestrate').val('');
      }
   }
 );

Fiddle is here