J. Coderino
J. Coderino

Reputation: 209

Jquery Output Odd Numbers skip

My function has an input and 2 outputs. It always has to start with a minimum input of 5, and that one needs to give me 3&4 in the outputs. and 6 gives 4&5. It also skips the odd numbers(it keeps the value of the last output when you give an odd number).

Only somewhere my code goes wrong. Because the function i need to replicate for example gives 53&54 as output when you put in 100. And mine just does -1 and -2 on the 100 so i get 98&97.

also i want 5 to give 3&4 and then when you put in 6 it needs to give 4&5, only i cant give it a value without 6 being NaN or 3&4 aswell.

This is what i need to duplicate (enter 5 in the left input field): https://www.schuttinggigant.com/

GIF of the function here: https://gyazo.com/6a65b65ee5bedddfe35851f78aa8dc27

My html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="InputField InputMeters">
  <input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator calcTotal" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" />
  <div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
Output:

<div class="SummaryRow">
  <strong>Schermen</strong>
  <input name="schermentotaal" type="text" id="schermentotaal" readonly="readonly" value="" />
</div>

<div class="SummaryRow">
  <strong>Palen en onderplaten</strong>
  <input name="schermentotaal2" type="text" id="schermentotaal2" readonly="readonly" value="" />
</div>

My Jquery:

 $(".calcTotal").on('input', function(elem) {
   let num = $(this).val();
   if (num % 2 !== 0) {
     num--;
   }


   $("#schermentotaal").val(num - 2);
   $("#schermentotaal2").val(num - 1);
 });

Update: I dont know how but MAYBE instead of -1 and -2 i need to do something procentages? - x%. just an idea.

Upvotes: 1

Views: 911

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44125

You're subtracting from num too many times when you're updating the HTML. Change your function to this:

$(".calcTotal").on('input', function() {
    let num = $(this).val();
    if (num % 2 === 0) {
        num--;
    }
    $("#schermentotaal").val(num - 1);
    $("#schermentotaal2").val(num);
});

All I changed was the last two lines, in case you're wondering.

Upvotes: 1

Shailesh Rathod
Shailesh Rathod

Reputation: 157

$(".calcTotal").on('input', function(elem) {
   let num = $(this).val();
   if (num % 2 === 0 && num > 2) { // why num>2 because num-2 will be 0 and you don't wont to display 0 
       $("#schermentotaal").val(num - 2);
       $("#schermentotaal2").val(num - 1);
   }
});

Upvotes: 0

Related Questions