user2758988
user2758988

Reputation: 139

How to bold text in rich text editor with [b] insteads of <b> using javascript or jquery

I'm making text editor for my project , i need to use this editor for forum , i'm making simple texteditor using javascript everything working fine . Problem is that i can't use <b></b> or <i></i> <u></u> because of htmlentities. My question is that how to bold text using [b][/b] instead of <b></b> or [i][/i] instead of <i></i> , i needed this very much. I need your help guys , Thanks.

Below Is My Code:

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

<style>
#my_textarea{
    width: 320px;
    height: 150px;
    border: thin solid #000;
    color: #000;
    padding: 10px;
    min-height: 150px;
    min-width: 320px;
    max-height: 150px;
    max-width: 320px;
}
#preview{
    width: 320px;
    height: 150px;
    border: thin solid #000;
    color: #000;
    padding: 10px;
}
</style>
<script type="text/javascript"> 
function formatText(tag) {
   var myTextArea = document.getElementById('my_textarea');
   var myTextAreaValue = myTextArea.value;
   var selected_txt = myTextAreaValue.substring(myTextArea.selectionStart, myTextArea.selectionEnd);
   var before_txt = myTextAreaValue.substring(0, myTextArea.selectionStart);
   var after_txt = myTextAreaValue.substring(myTextArea.selectionEnd, myTextAreaValue.length);
   myTextArea.value = before_txt + '<' + tag + '>' + selected_txt + '</' + tag + '>' + after_txt;
}
function preview() {
    var textbox , view ;
    textbox = document.getElementById('my_textarea');
    view = document.getElementById("preview");
    view.innerHTML = textbox.value
}

</script>
</head>

<body><br>
<form>
<input name="title" id="title" type="text" size="80" maxlength="80" /><br><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');" /> 
<input type="button" value="Unordered List" onClick="olist ('ul');" /><br><br>
<textarea name="my_textarea" id="my_textarea" style="width:300px;"></textarea><br>
<input type="submit" value="Submit" name="submit" id="submit" /><br><br>
</form>

<div id="preview"></div><br>
<button id="btn" onClick="preview();">Preview</button>

</body>

Demo : http://jsfiddle.net/aMR4M/

Upvotes: 2

Views: 1234

Answers (1)

ChristophT
ChristophT

Reputation: 510

I'm not sure if this is what you want, but you can use [ and ] and replace them with < and > when setting the innerHtml of your preview area.

view.innerHTML = textbox.value.replace(/\[/g, '<').replace(/\]/g, '>');

See http://jsfiddle.net/aMR4M/1/

Upvotes: 1

Related Questions