Вы можете просто установить текущее значение за вычетом самого себя с помощью оператора модуля.Вы можете определить лучшее событие, но blur
, вероятно, будет работать лучше.
let qty = document.getElementById('qty');
qty.onblur = function(){
let val = this.value; // Current Value
let step = this.getAttribute('step'); // Get step instead of hard coding it
this.value = (val - (val % step)).toFixed(2); // Simple math that adjusts the value on blur
}
<input type="number" id="qty" step=".72" />
Чтобы округлить один шаг, вы можете рассмотреть:
let qty = document.getElementById('qty');
qty.onblur = function(){
let val = this.value; // Current Value
let step = this.getAttribute('step'); // Get step instead of hard coding it
let roundDown = (val - (val % step)).toFixed(2);
let roundUp = (parseFloat(roundDown) + parseFloat(step)).toFixed(2);
this.value = roundUp;
}
<input type="number" id="qty" step=".72" />
Если вы хотите, чтобы это влияло только на шаги, которые не 1
, просто оберните это в операторе if:
let qty = document.getElementById('qty');
qty.onblur = function(){
let val = this.value; // Current Value
let step = this.getAttribute('step'); // Get step instead of hard coding it
if( step != 1 ){
let roundDown = (val - (val % step)).toFixed(2);
let roundUp = (parseFloat(roundDown) + parseFloat(step)).toFixed(2);
this.value = roundUp;
}
}
<input type="number" id="qty" step=".72" />