.net alternatives

by Michel Grootjans
posts - 66, comments - 123, trackbacks - 1

My Links

News

Shelfari: Book reviews on your book blog

Twitter












Archives

Post Categories

Thursday, January 27, 2011

Disable pasting in a textbox using jQuery

I had fun writing this one

My current client asked me to allow users to paste text into textboxes/textareas, but that the pasted text should be cleaned from '<...>' tags. Here's what we came up with:

    $(":input").bind('paste', function(e) {
        var el = $(this);
        setTimeout(function() {
            var text = $(el).val();
            $(el).val(text.replace(/<(.*?)>/gi, ''));
        }, 100);
    })
;

This is so simple, I'm amazed. The first part just binds a function to the paste operation applied to any input  declared on the page.

$(":input").bind('paste', function(e) {...});


In the first line, I just capture the element. Then wait for 100ms

setTimeout(function() {....}, 100);


then get the actual value from the textbox, and replace it with a regular expression that basically means replace everything that looks like '<{0}>' with ''. gi at the end are regex arguments in javascript.

/<(.*?)>/gi

Posted On Thursday, January 27, 2011 5:35 PM | Feedback (2) | Filed Under [ .net design ]

Powered by: