Very simply, I want to write some code that shows a list of buttons. When one is clicked, a chunk of predefined text is inserted into whichever text field the cursor is in at that moment. I can get the text to insert, but only in one text field.
I need this text to be expandable, as it will be used on several pages with different numbers of text field.
The code I have so far is below. I know I need to somehow insert the variable inFocus
from the second JavaScript function into the first parameter of the onClick="insertText()
function (currently just called txt1
).
Am I barking up the wrong tree or is this the correct way to go?
I’ve tried playing with the JavaScript in the main code and come up with this, to no avail. Any ideas?
<script type="text/javascript">
function insertText(text)
{
var elemID = false;
$('input, textarea').focus(function() {
elemID = $(this).attr('id');
});
var elem = document.getElementById(elemID);
elem.innerHTML += text;
}
</script>
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function insertText(elemID, text)
{
var elem = document.getElementById(elemID);
elem.innerHTML += text;
}
</script>
<script>
var inFocus = false;
$('input, textarea').focus(function() {
inFocus = $(this).attr('id');
});
$('#mybutt').click(function() {
alert('Cursor was last in element id: ' + inFocus);
});
</script>
</head>
<body>
<form>
<textarea cols="50" rows="10" id="txt1"></textarea><p>
<textarea cols="50" rows="10" id="txt2"></textarea></p>
<textarea cols="50" rows="10" id="txt3"></textarea>
<?php do { ?>
<input type="button" value="<?php echo $row_tooltips['word']; ?>" onclick="insertText('txt1', '<?php echo $row_tooltips['link']; ?>');">
<?php } while ($row_tooltips = mysql_fetch_assoc($tooltips)); ?>
</form>
</body>
</html>