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

220
Views
Jquery to allow negative and positive numbers on text field and negative sign should have 0 indexes

I need to validate a text field to accept only negative or positive numbers and indexing also matters. this is what I have tried so far.

this is HTML code

<input type="text" class="negativeaccept" >

here is Jquery

   $(document).on('keypress','.negativeaccept', function(event) {
   if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
        $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
   }  
   });

this code only accepts a positive number with a decimal. I want a negative sign (-) of The 0 indexes.

i try this code and its working (event.which != 45 || $(this).val().indexOf('-') != -1) && but negative (-)sign enter any index. can you try this better than this a solution.

$(document).on('keypress','.negativeaccept', function(event) {
    if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
            $(this).val().indexOf('.') != -1) && (event.which != 45 || $(this).val().indexOf('-') != -1) &&
             (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="negativeaccept">

about 4 years ago · Juan Pablo Isaza
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!