Formatting selected text

How would I be able to do this, but from a button… each time i’ve tried, it seems to deselect the text when i press on the button… thus the changes aren’t made. Should I store the selected in a variable and then when I call the function from the button it pulls in that variable?

What are your thoughts?

function doFormat() {
 var startIndex:Number = Selection.getBeginIndex();
 var endIndex:Number = Selection.getEndIndex();
 var stringToUppercase:String = output_txt.text.substring(startIndex, endIndex);
 var format2_fmt:TextFormat = new TextFormat();
 format2_fmt.bold = true;
 output_txt.setTextFormat(startIndex, endIndex, format2_fmt);
}

[FONT=Courier New]

[/FONT]