View Full Version : BBCode buttons

08-30-2004, 10:42 AM
i have my BBCode buttons working so when i am typing, i can press the B button and it puts where i am right then, but how do i get it so that in the Edit form of that same text, i can highlight some text and click the same B button and it will put [BOLD] and tags before and after the highlighted text?

and also, when i click the B button, it doesnt put the [BOLD] where my cursor currently is... it puts it at the end of the textarea's value

Willy Duitt
08-30-2004, 01:54 PM
Here, this should get you started...

It is currently IE only... To make it Mozilla compatable you will need to add support for: setSelectionRange, selectionStart, selectionEnd... If you can not do this yourself... Perhaps someone else would be willing to do this for you... But ATM, I do not have the time nor do I know what your form looks like so I am not going to waste my time writing something else which may not be what you are looking for....

<script type="text/javascript">
function setCaretPos(input){
input.caretPos = document.selection.createRange().duplicate();

function insertAtCaret (input,button) {
if(document.all && input.createTextRange){
if(input.caretPos && button.value.match(/(\*)?(\w+)/)){
if(input.caretPos.text.length == 0){
input.caretPos.text = '['+RegExp.$1.replace('*','/')+RegExp.$2+']';
button.value = (button.value == '*'+RegExp.$2) ? RegExp.$2 : '*'+RegExp.$2;
} else{ input.caretPos.text = '['+RegExp.$2+']'+input.caretPos.text+'[/'+RegExp.$2+']' };

<input type="button" value="B" onclick="insertAtCaret(this.form.text,this)">
<input type="button" value="I" onclick="insertAtCaret(this.form.text,this)">

<textarea name="text"
onkeyup="setCaretPos(this);" >
Click in this input anywhere and then press the buttons above. It will insert the BBcode at the caret position and change the button to indicate that the BBcode is open. Click anywhere again and it will close the open tag or you may choose another tag to open.

Additionally, you may highlight text and choose one of the buttons above and the selected text will be wrapped in the corresponding BBcode.</textarea>


08-30-2004, 06:08 PM
Gecko and IE compatible with nesting error checking: