Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery input value number and decimal only

Tags:

jquery

I want input field accept numbers and decimal only.

Input field should not accept negative, letters, symbols other than single decimal. Number 1 works absolutely fine with input type "text". However, number 2 doesn't work and the only difference is type as number.

I want numbers and decimals only. No negative, no letter and no symbol.

like image 420
Drozzy Avatar asked Jan 28 '26 15:01

Drozzy


1 Answers

All the keyboard keys have different ASCII code just creating a script which will except only number and decimals by recognising there acsii codes rest will be ignored

HTML

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

JS

$(document).ready(function() {
  $('.inputNumberDot').keypress(function(event) {
    var charCode = (event.which) ? event.which : event.keyCode

    if (
      (charCode != 45 || $(this).val().indexOf('-') != -1) && // “-” CHECK MINUS, AND ONLY ONE.
      (charCode != 46 || $(this).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
      (charCode < 48 || charCode > 57))
      return false;

    return true;

  });
});

Working example : https://jsfiddle.net/Luaq2f65/2/

like image 136
Gaurav Aggarwal Avatar answered Jan 30 '26 06:01

Gaurav Aggarwal



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!