JavaScript > Forms articles:
• How do I have the list of OPTIONs in a SELECT listbox change depending on the selection in another listbox?
Read
• How do I scroll a SELECT MULTIPLE input / listbox so that the SELECTED OPTION is visible?
Read
• How do use buttons to insert text (e.g. HTML tags) into a TEXTAREA at the cursor position?
• Solving the "form elements show through pop-up menu layer" problem
Read
|
Return to index of articles
How do use buttons to insert text (e.g. HTML tags) into a TEXTAREA at the cursor position?
Category: JavaScript
Category: Forms
This only supports newish version of Internet Explorer, probably not on the Mac. Set the third parameter to true if a closing tag should also be inserted like <B> </B>
<script language=javascript>
<!--
function markSelection ( txtObj ) {
if ( txtObj.createTextRange ) {
txtObj.caretPos = document.selection.createRange().duplicate();
isSelected = true;
}
}
function insertTag ( txtName, tag, enclose ) {
var closeTag = tag;
if ( enclose ) {
var attribSplit = tag.indexOf ( ' ' );
if ( tag.indexOf ( ' ' ) > -1 )
closeTag = tag.substring ( 0, attribSplit );
}
if ( isSelected ) {
var txtObj = eval ( "document.forms[0]." + txtName );
if (txtObj.createTextRange && txtObj.caretPos) {
var caretPos = txtObj.caretPos;
caretPos.text = ( ( enclose ) ? "<"+tag+">"+caretPos.text+""+closeTag+">" : "<"+tag+">"+caretPos.text );
markSelection ( txtObj );
if ( txtObj.caretPos.text=='' ) {
isSelected=false;
txtObj.focus();
}
}
} else {
// placeholder for loss of focus handler
}
}
//-->
</script>
<form>
<textarea name="tsttxt" ONSELECT="markSelection(this);" ONCLICK="markSelection(this);" ONKEYUP="markSelection(this);">
</textarea>
<input type="button" value="BOLD" onClick="insertTag ( 'tsttxt', 'b', true )">
<input type="button" value="PARAGRAPH" onClick="insertTag ( 'tsttxt', 'p', false )">
</form>
9/10/2002
Source: Visit
|