Grace B
Grace B

Reputation: 1406

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

Upvotes: 1

Views: 1675

Answers (3)

2winners
2winners

Reputation: 1

here is a modified version that you can let input any tag letter

function TextMod(textAreaId,input) {
        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();
            if(input == "br"){
                sel.text =  str + "</"+input+">";
            }
            else{
            sel.text = "<"+input+">" + str + "</"+input+">";
            }
            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));
        if(input == "br"){
            field.value = before  + selected + "</"+input+">" + after;
        }
        else{
            field.value = before + "<"+input+">" + selected + "</"+input+">" + after;
        }

    }

Upvotes: 0

Joe
Joe

Reputation: 82614

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;
    }

Upvotes: 1

GorillaMoe
GorillaMoe

Reputation: 4134

see what alex king's approach is: http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript

Upvotes: 0

Related Questions