In my form I want to allow the user to format text and add lists and such (basic html functionality, without having to know html).
Using the Bold button as an example:
<div class="goBold button">B</div>
<input type="text" name="txtMessage" />
<script>
$(".goBold").click(function() {
formatText("bold");
});
function formatText(formatType)
{
var input = $("#txtMessage");
var text = input.val();
var ss = input[0].selectionStart;
var se = input[0].selectionEnd;
if (formatType == "bold")
{
if (ss == se)
{
// there's no text in the textbox, so just write in the tags
input.val(text + "[b][/b]");
}
else
{
// surround the highlighted text with the tags
input.val(text.substr(0, ss) + "[b]" + text.substr(ss, se) + "[/b]" + text.substring(se, text.length));
}
}
}
</script>
While all this works, there is a slight problem:
Lets assume my text value for this textbox is
The quick red fox jumps over the lazy brown dog. This is the only sentence in the English language that uses all 26 letters of the alphabet
With the words all 26 letters highlighted, clicking the bold button will wrap the text in the tags, but it will also add a second copy of the text that exists after the selection.
I’m not sure why this is, can anyone provide any insight here?
TIA 🙂
You should use
substringeverywhere :(BTW, your selector should be
$("input[name=txtMessage]")– it has no id).