Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable 'Paste' in Android browser using JQuery?

I have an input field which I do not want users to paste any values in it. I am using the following jQuery code and it works fine on desktop Browser and iPhone Safari. The problem is it's not working on Android browser.

$('#no_paste').bind("paste", function(e) {                
        e.preventDefault();
});

Here's the fiddle

like image 681
CalebC Avatar asked Nov 12 '22 23:11

CalebC


1 Answers

I've tested this on Galaxy SIII and Android browser doesn't seem to send the paste event. However, it still sends the input event after something was pasted.

If user is typing into a field he will fire one input event for each letter. However, if he is pasting, input event will fire only once for the whole string that was pasted. Basing on this observation we can block pasting like this:

$('#ie').bind("input", function() {
    var previousValue = $(this).data('old_value') || '',
        newValue = $(this).val();

    if((newValue.length - previousValue.length) > 1) {
        $(this).val(previousValue);
    }

    $(this).data('old_value', $(this).val());
});

You will find JSFiddle here.

Please note that this will also block autocomplete and all other strange input techniques that work in a similar fashion (I don't know about any).

like image 153
Konrad Dzwinel Avatar answered Nov 15 '22 00:11

Konrad Dzwinel