Search code examples
jquerykey-bindings

jQuery Restricting certain numbers from being typed in a Bootstrap input


Okay, I did a mistake and blindly copied and pasted a ''code snippet' that is supposed to restrict the user from typing down ANYTHING ELSE other than a number in a Bootstrap input field.

By blindly doing that, i did not really understood how it's supposed to work. Now i need to allow the decimal point, the "." to be typed down and i don't know what i need to change.

Can someone explain the snippet below or provide a resource?

$('#elementXPosition,#elementYPosition,#elementWidth,#elementHeight').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();

});

Solution

  • Here is the solution I am able to create for you
    There are two possible solutions to go with and I would prefer to go with HTML's pattern feature.

    **HTML**  
    <input type="text" id="elementXPosition" pattern="[0-9.]+" title="Please enter decimal numbers only" placeholder="Using pattern" />
    <input type="text" id="elementYPosition" placeholder="Using jQuery" />  
    
    **jQuery**  
    $(document).ready(function () {
        $("#elementYPosition").keydown(function (e) {
            /*To check if shift key was pressed*/
            if (e.shiftKey == true) {
                e.preventDefault();
            }
            /*Allows some keys to be pressed*/
            if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105) || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 46 || e.keyCode == 190) {} else {
                e.preventDefault();
            }
            /*This will allow the '.' to be pressed only once*/
            if ($(this).val().indexOf('.') !== -1 && e.keyCode == 190) e.preventDefault();
    
        });
    });  
    

    Also here is the list of key codes you might need to edit the code as per your wish.
    Hopefully it helps.