clock  Mon - Sun 8.00 AM - 8.00 PM
fb
instagram
play store
pinterest

How To Allow Only Input Float Numbers Using jQuery

writter  Sumit Dey Sarkar
Date  23 Aug 2022
Language  JQuery
How To Allow Only Input Float Numbers Using jQuery

How To Allow Only Input Float Numbers Using jQuery

In this tutorial we will learn how to allow only input float numbers using jQuery and how to allow only numbers and numbers with two decimal place using jQuery.

let's see the examples - 

 

1) How to allow only numbers and numbers with two decimal place using jQuery

<!DOCTYPE html>
<html>

<head>
    <title>How to allow only numbers and numbers with two decimal place using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>

    <div class="container">
        <h1>How to allow only numbers and numbers with two decimal place using jQuery</h1>
        <input type="text" name="number" class="onlyNumber" autocomplete="off">
    </div>

</body>

<script>
    $('.onlyNumber').keypress(function (event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
            ((event.which < 48 || event.which > 57) &&
                (event.which != 0 && event.which != 8))) {
            event.preventDefault();
        }

        var inputValue = $(this).val();

        if ((inputValue.indexOf('.') != -1) &&
            (inputValue.substring(inputValue.indexOf('.')).length > 2) &&
            (event.which != 0 && event.which != 8) &&
            ($(this)[0].selectionStart >= inputValue.length - 2)) {
            event.preventDefault();
        }
    });
</script>

</html>

 

Output

jQuery

2) How to allow only input float numbers using jQuery

<!DOCTYPE html>
<html>

<head>
    <title>How to allow only input float numbers using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>

    <div class="container">
        <h1>How to allow only input float numbers using jQuery</h1>
        <input type="text" name="number" class="onlyNumber" autocomplete="off">
    </div>

</body>

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

</html>

 

Output

jQuery