Disable pasting in a textbox using jQuery
- by Michel Grootjans
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