I'm running the following code when a user clicks on a button to copy text from a series of paragraphs in a div into a text area input field. When the text area is empty, the code works correctly and pastes the paragraph text into the field. If I press the button again, it will repeat the function too, appending the paragraph text to the previously pasted text.
However, if I type anything manually into the text field and then click the button, it just doesn't work.
function copyDiv() {
var x = document.getElementById('post-caption').getElementsByTagName('p');
var i;
var firstDivContent = x[0].innerHTML;
for (i = 1; i < x.length; i++) {
firstDivContent = firstDivContent + x[i].innerHTML;
}
var secondDivContent = document.getElementById('comment');
firstDivContent = firstDivContent + " " + secondDivContent.innerHTML;
secondDivContent.innerHTML = firstDivContent;
}
The corresponding HTML is as follows:
<div class="entry themeform" id="post-caption">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
<input name="submit" type="submit" id="submit" class="submit" value="Send Feedback">
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"> </textarea></p>
<input name="copy-text" id="copy-text" class="submit copy-text" value="Copy caption text" onClick="copyDiv();">
Any help is greatly appreciated.