Restrict input to number only on pasting

后端 未结 7 776
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 21:54

I have an input filed with a class called restrict-numbers which i want to restrict the entered characters to only accept numbers, i used the following code which is great b

7条回答
  •  清歌不尽
    2021-01-18 22:33

    Implement your form with jquery.numeric plugin.

    $(document).ready(function(){
        $(".numeric").numeric();
    });
    

    Moreover this works with textareas also!

    Or better change the input when user tries to submit,

    $('form').submit(function () {
        if ($('#numeric').value != $('#numeric').value.replace(/[^0-9\.]/g, '')) {
           $('#numeric').value = $('#numeric').value.replace(/[^0-9\.]/g, '');
        }
    });
    

    That's what you are doing, you want to remove the characters, other than numbers, so why make so much efforts, just remove them at the end.

    And here is my favourite option,

    Try the HTML5 number input:

     
    

    For non-compliant browsers there are Modernizr and Webforms2 fallbacks.

    or

    You may bind "paste" action to a function too,

    $( "#input" ).on("paste", function() {
        if ($('"#input').val() != $('"#input').val().replace(/[^\d\.]/g,"")) 
        { $('"#input').val($('"#input').val().replace(/[^\d\.]/g,""));
        }
    });
    

提交回复
热议问题