How To Allow Only Input Float Numbers Using jQuery

AuthorSumit Dey Sarkar

Pubish Date23 Aug 2022

categoryJQuery

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

Comments 0

Leave a comment