0

I need to insert floating value in textbox allow only 0-9 & signal dot(.)

I have tried this code:

<html>
<head>

 <script type="text/javascript" language="javascript"> 

    function isNumberKey(evt) { 
         var charCode = (evt.charCode) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
             return false;
        }
 </script> 


</head>
<body>
<input type="text" id="txtChar" onkeypress="return isNumberKey(event)"  name="txtChar" class="CsstxtChar" maxlength="4"/>
</body>
</html>

3 Answers3

0

jQuery(document).ready(function() {
    $('.float-number').keypress(function(event) {
        if ((event.which != 46 || $(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>
    <html>
      <body>
        Enter Number:
        <input type="text" name="number" value="" class="float-number">
      </body>
    </html>
Nirav Sutariya
  • 317
  • 4
  • 14
0

You can try this code

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>

<body>

    <input type="text" id="txtChar" name="txtChar" class="CsstxtChar" maxlength="4" />
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script>
        $('.CsstxtChar').keypress(function (event) {
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
        });

    </script>
</body>

</html>

Thanks

piet.t
  • 11,718
  • 21
  • 43
  • 52
HaSnen Tai
  • 1,353
  • 2
  • 14
  • 22
0

I would suggest you to use regexp instead:

const pattern = new RegExp('[0-9.]');

$('#txtChar').on('keypress', function(e){
 const res = pattern.test(e.key);
 if(!res) {
  e.preventDefault();
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtChar" name="txtChar" class="CsstxtChar" maxlength="4"/>
dganenco
  • 1,596
  • 1
  • 5
  • 16