Just for fun, I want to build simple text formatting tools for a textarea. To begin, I want to be able to enclose high-lighted text in a textarea with ** if it is to be in bold format (just like stackoverflow’s textarea editor). I’ve written the following code, which works most of the time, but it does have a bug, which I’ll explain shortly.
<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var tmpText = '';
$(document).ready(function(){
tmpText = '';
$('#btn_bold').click(function(){bold(tmpText);});
$('textarea').bind('mouseup', function(){
tmpText = '';
if(window.getSelection){
tmpText = window.getSelection().toString();
}else if(document.getSelection){
tmpText = document.getSelection().toString();
}else if(document.selection){
tmpText = document.selection.createRange().text;
}
});
});
function bold(str)
{
$('textarea').val($('textarea').val().replace(str,'**'+str+'**'));
}
</script>
</head>
<body>
<button type="button" id="btn_bold">bold it</button>
<textarea>AA</textarea>
</body>
</html>
So if you high-light the first letter A and bold it, you’ll get the result **A**A. But if you high-light the second letter A and bold it, you still get **A**A, instead of A**A** because the line of code $('textarea').val($('textarea').val().replace(str,'**'+str+'**')); is insufficient at identifying which letter A you want to bold.
What’s an efficient way to identify high-lighted text and bold it?
I’ve written a jQuery plug-in that does this that I can extract out to a standalone script if it would help. An example of using the plugin to replace selected text with the word “hello”.
Also, as I commented in a related question of yours, the function you have there won’t work for textareas, which have a separate mechanism for dealing with selections. See my answer there for a function that will work.