Just for fun, I want to create simple text formatting tools for a text field. For starters, I want high-light text to be added to the textarea text if it should be bold (like the textovera stackoverflow editor). I wrote the following code, which works most of the time, but it has an error, which I will talk about in the near future.
<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>
, A , **A**A. A , **A**A A**A**, $('textarea').val($('textarea').val().replace(str,'**'+str+'**')); , A .
?