2

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.

Ayush Oli
  • 49
  • 2
  • 8

1 Answers1

1

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 );
  ...
}
caiovisk
  • 3,667
  • 1
  • 12
  • 18
  • Hey, thank you so much for the answer. But I have a slight problem. Since my input field will have value=" ' . get_the_title( $post_id ) . ". All the buttons are copying the first title. So, do I have to loop the function? Because the copied text should be the title. But I am getting the same title as the first. – Ayush Oli Feb 04 '19 at 03:24
  • Hey man, this is working. So, really thank you very much. Appreciate a lot. If any other things come on the way. I'm gonna tell you. Thank you again. See ya. – Ayush Oli Feb 04 '19 at 10:30