So, I have a CPT and I have added some Custom Columns in the backend. I have this button at the side and it should copy the title. I was using Javascript for this and it is not working.
function myFunction() {
var copyText = document.getElementById("clickTitle");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
.click-title{
display: none;
}
echo the_title( '<h4 class="click-title" id="clickTitle">', '</h4>' );
echo '<button class="btn btn-danger btn-sm" onclick="copyFunction()">Copy Title</button>';
But it is not working. I want the button to copy the title and I can't find a way to do that. I tried more than that.
(Click here to view image) I want to copy the title when I click Copy Title button.
Select only works on input text field elements
So, set a input
hidden field next to your title.
function copyFunction() {
var copyText = document.getElementById("clickTitle");
copyText.select();
document.execCommand("copy");
alert(copyText.value);
}
<h4 class="click-title">This is the title to be copied.</h4>
<input id="clickTitle" type="text" value="This is the title to be copied">
<button class="btn btn-danger btn-sm" onclick="copyFunction()">Copy Title</button>
To work inside a loop, a little change should be done.
Give a unique ID for each input field:
<input id="clickTitle-<?php echo $post_id; ?>" type="text" value="This is the title to be copied">
Call the method by passing the desired ID:
<button class="btn btn-danger btn-sm" onclick="copyFunction(<?php echo $post_id; ?>)">Copy Title</button>
Then update the function to look for the right id.
function copyFunction( elId ) {
var copyText = document.getElementById("clickTitle-" + elId );
...
}