Insert text into specific area of textarea field

The example below is used to inject html bold, italic and hyperlink tags around the highlighted text in a field.
HTML • JavaScript • Lotus Notes Form

JS HEADER

var formattedStr = "";
startPosition = 0;
var endPosition = 0;

function insertBoldTags(myField){
	findPositions(myField);
	var text = myField.value;
	if (startPosition!=endPosition) {
		var sbStr = text.substring(startPosition,endPosition);
		sbStr = '<b>'+ sbStr + '</b>';
		fillsFormattedString(text,sbStr,myField);
	}
}

function insertItalicTags(myField){
	findPositions(myField);
	var text = myField.value;
	if (startPosition!=endPosition) {
		var sbStr = text.substring(startPosition,endPosition);
		sbStr = '<i>'+ sbStr + '</i>';
		fillsFormattedString(text,sbStr,myField);
	}
}

function insertLinkTags(myField){
	findPositions(myField);
	var text = myField.value;
	if (startPosition!=endPosition) {
		var sbStr = text.substring(startPosition,endPosition);
		sbStr = '<a target="_blank" href="http://' + sbStr + '">'+ sbStr + '</a>';
		fillsFormattedString(text,sbStr,myField);
	}
}

function findPositions(myField){
	var text = myField.value;
	if (document.selection) {
		// Internet Explorer
		var range = document.selection.createRange();
		var dpl = range.duplicate();
		if (range.text.length > 0) {
			dpl.moveToElementText(myField);
			dpl.setEndPoint("EndToEnd", range);
			startPosition = dpl.text.length-range.text.length;
			endPosition = startPosition + range.text.length;
		}
	}
	else {
		// Mozilla Firefox
		startPosition = myField.selectionStart;
		endPosition = myField.selectionEnd;
	}
}

function fillsFormattedString(text, selectedText, myField){
	// split textarea value into three pieces: before startPosition,
       // startPosition until endPosition, and after endPosition
	var str1 = text.substring(0,startPosition);
	var str2 = text.substring(startPosition,endPosition);
	var str3 = text.substring(endPosition,text.length);
	// replace str2 with formatted substring (selectedText)
	str2 = selectedText;
	// form the new string
	formattedStrWithBrackets = str1 + '[' + str2 + ']' + str3;
	formattedStrNoBrackets = str1 + str2 + str3;
	myField.value = formattedStrWithBrackets;
}

Here's the JavaScript to place in your buttons. One for BOLD, ITALICS, and LINKS.

insertBoldTags(document.getElementById('Body1'));

Written by Frank Joseph Brefere III

Posted by fbrefere001 on Tuesday July 29, 2008