Protect Text within Textarea

This exact code protects text in a textarea that was present before editing & should remain at the beginning of the text area. In the case of @ mentioning someone, you could have the text box include that text (and be a 1:1 representation of what will be posted) while preventing it from being deleted by the user.

originalText = jQuery('textarea').val();
jQuery('textarea').on('change keydown keyup blur',function(){
currentText = jQuery('textarea').val();
if(currentText.indexOf(originalText) === -1 && currentText.indexOf(originalText.substring(0,originalText.length-1)) !== -1) // If it's just the last character that got deleted (via backspace)
jQuery('textarea').val(currentText+originalText.substring(originalText.length-1,originalText.length)); // Add that character back
else if(currentText.indexOf(originalText) === -1) // If it's no longer there
jQuery('textarea').val(originalText+currentText); // Add it back to the front
});

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.