samedi 3 octobre 2015

Javascript Subtracting Value Of Input Fields If Checkbox Is Checked

I have three inputs that are both text and one checkbox.

I would like it to where if the checkbox is checked the value of input A is subtracted from input B and shows up in input C.

I am also wanting it to change if new numbers are entered.

Basically:

1: If checkbox is checked subtract value A from value B.

2: If checkbox is checked subtract value A from value B on keypress.

I've tried this:

$('#autoCal').change(function () {
 var start = +$("#start").val();
 var end = +$("#end").val();
 $("#result").val(end-start);

 if ($(this).attr("checked")) {
    $("#end").keyup(function(){
    var start = +$("#start").val();
    var end = +$("#end").val();
    $("#result").val(end-start);
    return;
    });
    });
});

autoCal is the checkbox. start is value A. end is value B. result is value C.

<fieldset data-step="3" data-intro="How many miles did you go? Let us know by filling out this section.">
     <legend>Mileage</legend>
      <label for="oStart"><span>Odometer Start<span class="required">*</span></span><input type="text" name="oStart" class="shortInput" id="start"></label>
      <label for="oEnd"><span>Odometer End<span class="required">*</span></span><input type="text" name="oEnd" class="shortInput" id="end"></label>
      <label for="mileage"><span>Total Miles<span class="required">*</span></span><input type="text" name="mileage" class="shortInput" id="result"></label>
      <label for="autoCal"><span>Auto calculate milage?</span><input type="checkbox" id="autoCal" name="autoCal"></label>
    </fieldset>




Aucun commentaire:

Enregistrer un commentaire