SajZ
SajZ

Reputation: 260

Increment of input type number appending number instead of incrementing

During the first time, it's incrementing correctly. However, using arrows if the values are changed, then the button increment is appending text instead of incrementing it.

var visits = 100;

function incrementStep(data) {
  visits = visits + data;
  $('#visits').val(visits);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="visits" value="100" step="100">
<span onclick="incrementStep(500)">500</span>

Upvotes: 1

Views: 198

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

At no point is anything appended as the relevant variables hold numeric data types.

The issue is because the incremented value is stored in the visits variable. As soon as you manually increment/decrement the displayed value by clicking an up/down arrow the value in the control and the value in vists goes out of sync. Hence the next time you click the span the value is not what you expect it to be.

To fix this get rid of the global variable, as they are bad practice anyway, and increment the value in the control as read directly from the DOM:

jQuery($ => {
  $('span').on('click', function() {
    $('#visits').val((i, v) => parseInt(v, 10) + 500);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="visits" value="100" step="100">
<span>500</span>

Note the use of an unobtrusive event handler in this example. Using inline onX attributes is no longer good practice and should be avoided where possible.

Upvotes: 1

Related Questions