Replace Text in jQuery -
html:
<textarea></textarea><br /> <a href="#">generate</a> <span id="output"></span>
jquery:
$('textarea').bind('keypress', function(event) { var charcode = event.which; var keychar = string.fromcharcode(charcode); return /[a-za-z ]/.test(keychar); }); var replacements = { 'a': '1', 'b': '2', 'c': '3' } $('a').click(function() { $('textarea').val(function(i, val) { val = val.split(''); $.each(val, function(i, e) { val[i] = replacements[e] ? replacements[e] : e; }); return val.join(''); }); return false; });
how can modify existing code display replacement in $('span#output');
? , side question, modifications can made make code more efficient?
here solution display replacement in #output :
$('textarea').bind('keypress', function(event) { return /[a-za-z ]/.test(string.fromcharcode(event.which)); }); var replacements = { 'a': '1', 'b': '2', 'c': '3' } $('a').on('click', function(e) { e.preventdefault(); val = $('textarea').val().split(''); $.each(val, function(i, e) { val[i] = replacements[e] ? replacements[e] : e; }); $('#output').html(val.join('')) ; });
Comments
Post a Comment