javascripthtmltextarea

Button to insert tags to textarea


I believe this has been answered before but how can I have buttons / images / whatever so that when I click them it inserts the <b></b> around the cursor position like what you find in forums (and even the StackOverflow ask a question page)?
Again, I know this has been answered but all I could find was using jQuery and my server does not support it...
Thanks


Solution

  • Here's one I wrote awhile ago jsFiddle

        function boldText(textAreaId, link) 
        {
            var browser=navigator.appName
            var b_version=navigator.appVersion
    
            if (browser=="Microsoft Internet Explorer" && b_version>='4')
            {
                var str = document.selection.createRange().text;
                document.getElementById(textAreaId).focus();
                var sel = document.selection.createRange();
                sel.text = "<b>" + str + "</b>";
                return;
            }
    
            field = document.getElementById(textAreaId);
            startPos = field.selectionStart;
            endPos = field.selectionEnd;
            before = field.value.substr(0, startPos);
            selected = field.value.substr(field.selectionStart, (field.selectionEnd - field.selectionStart));
            after = field.value.substr(field.selectionEnd, (field.value.length - field.selectionEnd));
            field.value = before + "<b>" + selected + "</b>" + after;
        }