Does 开发者_运维技巧anyone know a possibilty to protect a string-wildcard from changing in a textarea?
HTML:
<textarea name="mail_text" id="mail_text">
{salutation} {recipient},
thanks for your email.
Regards
{username}
</textarea>
I would like to catch when someone tries to change one of the wildcards: {salutation},{recipient} and {username}
$("textarea").keyup(function() {
var val = $(this).val();
//protect the wildcards
});
Thanks!
You can't practically ‘protect’ part of a textarea. Naïvely you could try to block input keypresses when the cursor is inside a {...}
pattern, but there are so many other ways it could be edited, eg. select range then delete/replace, cut/copy/paste, drag and drop...
It might be better simply to monitor the textarea's value, and show a warning underneath it when there's something about the value that's wrong, eg.:
<textarea id="mail_text">...</textarea>
<div id="mail_text_warning"></div>
<script type="text/javascript">
function checkMailText() {
var tokens= ['username', 'recipient', 'salutation'];
var value= $('#mail_text').val();
var problems= [];
$.each(tokens, function() {
if (value.split('{'+this+'}').length!==2)
problems.push('Please ensure there is one and only one {'+this+'} token present in the text');
});
matches= value.match(/\{[^\}]*\}/g);
if (matches!==null) {
$.each(matches, function() {
for (var i= tokens.length; i-->0;)
if ('{'+tokens[i]+'}'===this)
return;
problems.push('Token '+this+' is not known');
});
}
$('#mail_text_warning').text(problems.join('. '));
}
setInterval(checkMailText, 500);
</script>
Make all easier.
Create two textareas: one with information where user can write ("thanks for your email. Regards." etc). And another one with wildcards or end results if it is possible. You can modify the second textareas immediately after user type (use keydown or keyup event).
精彩评论