I found some code on stackoverflow that inserts text from a text input field into a textarea at the cursor location.
What I want to do is modify this working code so the user can enter a URL with Title text into two form input fields, build a complete hypertext link from the input and insert the resulting HTML for the anchor tag into the textarea as a complete link at the cursor position, just like what happens when you click the insert URL button in a wysiwig editor.
How would I modify the code below to accomplish this?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Page</title>
<script type="text/javascript">
window.onload = function()
{
btn = document.getElementById("btnInsertText");
myText = document.getElementById("myTextArea");
text = document.getElementById("textToInsert");
btn.onclick = function()
{
insertAtCursor(myText, text.value);
}
}
function insertAtCursor(myField, myValue)
{
//IE support
if (document.selection)
{
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//Mozilla/Firefox/Netscape 7+ support
else if (myField.selectionStart || myField.selectionStart == '0')
{
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValue
+ myField.value.substring(endPos, myField.value.length);
}
else
{
myField.value += myValue;
}
}
</script>
</head>
<body>
Text To Insert: <input type="text" id="textToInsert" />
<input type="button" id="btnInsertText" value="Insert Text" /><br />
<br />
<textarea id="myTextArea" rows="6" cols="50">
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
</textarea>
</body>
</html>