Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
Html textbox that prevents user from entering negative numbers rounds up positive decimal numbers

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Just use a regular expression to strip all non-numberic digits.

  • Not allow period(.) = string.replace(/[^0-9]/g, '')
  • Allow period(.) for decimals = string.replace(/[^\d.-]/g, '')

<div class="box-tricks">
 <input type="number" min="0" oninput="this.value = this.value.replace(/[^0-9]/g, '')"> 
</div>

about 4 years ago · Juan Pablo Isaza Report

0

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)">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!