简体   繁体   中英

How to add <b></b> <i></i> tags to selected text in a textarea in all browsers?

How to create some javascript to do the following - when the user clicks the "BOLD" button, the selected text gets a " <b> " and a " </b> " wrapped around it. This code work only in IE. How to work this thing in all browsers.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

</head>

<body>
<script type="text/javascript"> 
function formatText (tag)
{
    if (typeof document.selection != "undefined")
    {
            var selectedText = document.selection.createRange().text;
            if (selectedText != "")
            {
                var newText = "<" + tag + ">" + selectedText + "</" + tag + ">";
                document.selection.createRange().text = newText;
            }
    } 
}
</script> 
    <textarea name="my_textarea"></textarea><br /> 
    <input type="button" value="bold" onclick="formatText ('b');" /> 
    <input type="button" value="italic" onclick="formatText ('i');" /> 
    <input type="button" value="underline" onclick="formatText ('u');" />     
</body>
</html>

Demo : http://jsfiddle.net/9kULw/6/
Note : Demo works only in IE

This seems to do it: http://jsfiddle.net/9kULw/10/

function formatText(tag) {
    var myTextArea = document.getElementById('my_textarea');
    var myTextAreaValue = myTextArea.value;
    var updatedText = '<'+tag+'>' + myTextAreaValue + '</'+tag+'>';
    myTextArea.value = updatedText;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM