Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a number input so the first two numbers become decimals with oninput

This may have been answered already, but I can't find it. I am making a form with a number input that will be used to submit an item price (with two decimal places). I want this to be done without having to manually enter the decimal. ideally with some oninput inline javascript. I was playing with the math function but am still new to javascript and am having no luck.

If you enter 1 it should automatically become 0.01

... or 12 becomes 0.12

... 123 becomes 1.23 etc.

Thanks for any help!

<input type=number min=0.00 max=100.00 step=0.01 class='detailsInput' id='priceEntry' name='priceEntry' placeholder='Enter Price' oninput='(Math.round(priceEntry*100)/100)(this)'>
like image 710
Michael Davis Avatar asked Dec 15 '25 07:12

Michael Davis


1 Answers

Just take the "actual value" of the input. Make sure to remove any decimal dot.... Parse it as an integer and divide by 100. Return. ;)

document.querySelector(".detailsInput").addEventListener("input", function(e){
  let actualValue = e.target.value.replace(".","")
  e.target.value=parseInt(actualValue)/100
})
<input type=number min=0.00 max=100.00 step=0.01 class='detailsInput' id='priceEntry' name='priceEntry' placeholder='Enter Price'>

=== Ho! If you insist on an inline version:

<input type=number min=0.00 max=100.00 step=0.01 class='detailsInput' id='priceEntry' name='priceEntry' placeholder='Enter Price' oninput="this.value=parseInt(this.value.replace('.',''))/100">
like image 63
Louys Patrice Bessette Avatar answered Dec 16 '25 23:12

Louys Patrice Bessette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!