Geeks With Blogs

@michelgrootjans
  • michelgrootjans I scored 14 points in the FizzBuzz challenge on HackerRank https://t.co/8vicb8ANPq about 532 days ago
  • michelgrootjans @yreynhout we implemented elasticsearch on our last project. Works like a charm for rails apps. about 537 days ago
  • michelgrootjans Microsoft releases glasses - implementation looks great - https://t.co/RoC1s02irE about 539 days ago

News
Shelfari: Book reviews on your book blog

.net alternatives 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
Posted on Thursday, January 27, 2011 5:35 PM .net , design | Back to top


Comments on this post: Disable pasting in a textbox using jQuery

# re: Disable pasting in a textbox using jQuery
Requesting Gravatar...
check out the .live() method... that would make sure that your handler code would also be used for any input elements that are dynamically added to the DOM after the code above has executed :)
Left by Davy Brion on Jan 28, 2011 10:10 AM

# re: Disable pasting in a textbox using jQuery
Requesting Gravatar...
Indeed.

Found this article comparing both http://blogs.msdn.com/b/dorischen/archive/2011/01/28/jquery-tips-bind-or-live.aspx
Left by Michel Grootjans on Jan 30, 2011 10:31 AM

# re: Disable pasting in a textbox using jQuery
Requesting Gravatar...
$(":input").bind('paste', function(event) {
event.preventDefault();
event.originalEvent.preventDefault();
event.originalEvent.cancelBubble = true;
})
Left by Navaneeth on Oct 08, 2012 12:56 PM

Your comment:
 (will show your gravatar)


Copyright © Michel Grootjans | Powered by: GeeksWithBlogs.net | Join free