Disable copy paste of alphabets in text field using jquery

后端 未结 6 1844
遇见更好的自我
遇见更好的自我 2021-01-14 05:33

In my project i have text field that only take numeric value.but when I copy an alphabets using ctl+c and paste using ctl+v it will allow the alphabets in the text field.So

6条回答
  •  青春惊慌失措
    2021-01-14 05:54

    After looking at the event object and "duckduckgoing" a bit:

    $('input').on('paste', function (event) {
        if (event.originalEvent.clipboardData.getData('Text').match(/[^\d]/)) {
            event.preventDefault();
        }
    });
    

    I've got no idea how cross-browser this is but if backwards compatibility is no issue go ahead and use it.

    Check it out at codepen

    PS: I'm using google chrome version 22 on mac os 10.6

    EDIT: firefox 13 does not have the clipboardData object, ie 10 neither, safari 5.1.2 supports it (so it's a webkit feature).

提交回复
热议问题