I have this code that prevents the user from entering negative weights in the Weight textbox.
<input type="number" min="0"
oninput="this.value = !!this.value && Math.abs(this.value)>= 0 ? Math.abs(this.value) : null">
Scenario 1 is working fine: Input: 1.23 Output 1.23
Scenario 2: Input: 0.05 Output 5 (I would like to get 0.05)
When I enter decimal numbers like 0.04 or 0.05, I am getting 4 or 5. I would like to get the decimal numbers as it is.
Just use a regular expression to strip all non-numberic digits.
string.replace(/[^0-9]/g, '')string.replace(/[^\d.-]/g, '')<div class="box-tricks">
<input type="number" min="0" oninput="this.value = this.value.replace(/[^0-9]/g, '')">
</div>
You are probably better off with using onblur instead of oninput as this will give the user the opportunity to complete his input before it gets "mutilated" by the event handler. I also changed the input type to "text" as this will require the decimal dot "." to be entered - independently from any locale setting that might apply to your (or you users') browsers.
<input type="text"
onblur="this.value = !!(+this.value) && Math.abs(+this.value)>= 0 ? Math.abs(+this.value).toFixed(2) : null;console.log(this.value)">