Validate textbox by allowing only numbers and floats using jQuery

I am trying to check my asp.net text box to only accept numbers and '.'
To do this, I wrote a function using the Internet (sorry I'm new to jQuery)
Jquery

$('#<%= txtWidth.ClientID %>').keypress(function (event) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
}
});
});

It works fine, but Delete and Backspace do not work. How to enable the inclusion of these keys with keys? What changes do I need to make?

Please help this newbie ..

+4
source share
2 answers

Hope it's you! Will work on both FireFox and Google Chrome, as expected.

$('#<%= txtWidth.ClientID %>').keypress(function (event) {
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && (event.which != 8)) {
                event.preventDefault();
            }
        });
+4

: -

: -

$(function () {
  $("#abc").keydown(function (event) {
 console.log(event.keyCode);
    if (event.shiftKey == true) {
      event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
      event.preventDefault();
    }

    if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
      event.preventDefault(); 
      //if a decimal has been added, disable the "."-button

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="abc"/>
Hide result
+3

Source: https://habr.com/ru/post/1682014/


All Articles