I would change your HTML to generate some kind of ID that can be used to reference the element with your text.
<c:forEach items="${items}" var="item" varStatus="loop">
<h2 id="item-desc-${loop.index}">${item.itemDescription}</h2>
<input class="big-button" data-desc-ref="item-desc-${loop.index}" type="button" value="Add item copied to clipboard" id="btn" onclick="status(this)">
</c:forEach>
Above I added code to generate a unique id (e.g. id="item-desc-0"
) on each <h2>
element. On the button, I added a data-
attribute to reference the ID of the <h2>
so we can retrieve it later.
Now we change your status
function to find the element by the ID specified in the data attribute, and get its innerText
(the content between the opening and closing tags).
Then, you can pass that text to the function that copies it to the clipboard, reference above in my comment.
function status(clickedBtn)
{
var text = document.getElementById(clickedBtn.dataset.descRef).innerText;
copyToClipboard(text);
clickedBtn.value = "Copied to clipboard";
clickedBtn.disabled = true;
clickedBtn.style.color = 'white';
clickedBtn.style.background = 'gray';
}
Here's a working example. I had to put in sample HTML that would be generated by your loop.
function copyToClipboard(text) {
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}
function status(clickedBtn) {
var text = document.getElementById(clickedBtn.dataset.descRef).innerText;
copyToClipboard(text);
clickedBtn.value = "Copied to clipboard";
clickedBtn.disabled = true;
clickedBtn.style.color = 'white';
clickedBtn.style.background = 'gray';
}
<h2 id="item-desc-0">Testing 0</h2>
<input class="big-button" data-desc-ref="item-desc-0" type="button" value="Add item copied to clipboard" id="btn" onclick="status(this)">
<h2 id="item-desc-1">Testing 1</h2>
<input class="big-button" data-desc-ref="item-desc-1" type="button" value="Add item copied to clipboard" id="btn" onclick="status(this)">
<h2 id="item-desc-2">Testing 2</h2>
<input class="big-button" data-desc-ref="item-desc-2" type="button" value="Add item copied to clipboard" id="btn" onclick="status(this)">
` item and pass that.
– Cᴏʀʏ Nov 11 '18 at 22:07