views:

39

answers:

3

I have a 3 fields: Total amount Recurring amount Occurrences

A user will always enter occurrences, but has the choice of entering either total amount or recurring amount.

The equation for this is really simple: Occurrences * Recurring Amount = Total Amount

I need help making a Javascript function which if the user starts to type in the total amount field, recurring amount becomes disabled. The same is true if they enter recurring amount first. Once the user has input occurrences and either of the amounts, the remaining amount should be calculated and replace the disabled field.

I need the function to be able to allow the user to change any of the numbers, and have the calculation be re-done. Also, if the user totally removes a value from an amount, the other amount field should become active again.

I've never written Javascript code before, only edited. Any help to point me in the right direction is appreciated. Thanks

+2  A: 

Not sure why you think disabling fields is a good idea. I think user experience-wise it would be better to allow them to edit any field at any time, adjusting the other fields as needed.

<input id="recurring" onchange="onRecurEdit()"> * 
<input id="occurences" onchange="onOccurEdit()"> =
<input id="total" onchange="onTotalEdit()">
<script>      
  var recur = document.getElementById('recurring');
  var total = document.getElementById('total');
  var occur = document.getElementById('occurences');

  function onTotalEdit() {
    recurring.value = total.value / occur.value;
  }

  function onRecurEdit() {
    total.value = occur.value * recur. value;
  }

  function onOccurEdit() {
    total.value = occur.value * recur. value;
  }
</script>
levik
That's fine too. The important part is the calculation.
clang1234
Added some sample code.
levik
+1  A: 

This won't be perfect but it should be a decent start:

You can view an interactive demo of this code at http://jsfiddle.net/qzxf7/

You haven't given us your HTML so I'm going to assume you're using something like this:

<form action="" method="POST">
  <input type="text" name="occurences" id="occurences" value="" />
  <input type="text" name="recurringAmt" id="recurringAmt" value="" />
  <input type="text" name="totalAmt" id="totalAmt" value="" />
</form>

If you haven't dealt with Javascript before, I'm going to recommend you use jQuery which is a matter of importing the jQuery script in your HTML <head>.

Using jQuery you could start with code like this which is overly complicated but throws you into how to handle the disabled stuff as well as value updates.

/* On page contents loaded */
function updateForm() {
  var occ = $('#occurences');
  var occV = parseFloat(occ.val());
  occV = occV >= 0 ? occV : 0;
  var rec = $('#recurringAmt');
  var recV = parseFloat(rec.val());
  recV = recV >= 0 ? recV : 0;
  var tot = $('#totalAmt');
  var totV = parseFloat(tot.val());
  totV = totV >= 0 ? totV : 0;

  /* If total is disabled */
  if (tot.attr("disabled")) {
      if (rec.val() == '') { /* if no text in rec */
        tot.removeAttr("disabled"); /* Reenable total */
        tot.val('');
        return;
      }
      /* Otherwise update total */
      tot.val(recV * occV);
      return;
  }

  /* If rec is disabled */
  if (rec.attr("disabled")) {
      if (tot.val() == '') { /* if no text in total */
        rec.removeAttr("disabled"); /* Reenable rec */
        rec.val('');
        return;
      }
      /* Otherwise update rec watching for divide by zero error */
      rec.val(occV > 0 ? totV / occV : 0);
      return;
  }

  /* Otherwise neither disabled */

  if (recV > 0) { /* if rec has a number value */
      tot.attr("disabled", true); /* disable total */
      tot.val(recV * occV); /* update total */
      return;
  }


  if (totV > 0) { /* if total has a number value */
      rec.attr("disabled", true); /* disable rec */ 
      /* Update rec watching for divide by zero error */
      rec.val(occV > 0 ? totV / occV : 0);
      return;
  }
}

$(document).ready(function() {
  $('#occurences').keyup(function(){
    updateForm();
  });
  $('#totalAmt').keyup(function(){
    updateForm();
  });
  $('#recurringAmt').keyup(function(){
    updateForm();
  });
});
Graphain
This worked perfectly. And thanks for the live demo. I've bookmarked jsfiddle. Seems handy
clang1234
+2  A: 

Here's partly what you may be looking for: The code uses JQuery

JS code:

     $(document).ready(function() {

           function roundNumber(num, dec) {
              var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
              return result;
           }

           function calculateTot(evt) {
              var o = Number($("#occur").val());
              var a = Number($("#recAmt").val());

              if(!isNaN(0) && !isNaN(a)) {
                 var tot = roundNumber(o * a, 2);
                 $("#totalAmt").val(tot);
              }else {
                 $("#totalAmt").val("0");
              }
           }

           $("#occur").bind("change", calculateTot);
           $("#recAmt").bind("change", calculateTot);

     });

HTML for the same:

     <input type="text" id="occur" /> *
     <input type="text" id="recAmt" /> =
     <input type="text" id="totalAmt" readonly="readonly" />
naikus