0

I'm trying to change button text on button click so that the text changes from 'Copy' to 'Copied!' as part of a custom clipboard setup. Here is the code I'm using:

HTML:

<button id="copyButton2">Copy</button>

JS:

<script>
 jQuery(".copyButton2").click(function () {
            jQuery(this).text(function(i, v){
               return v === 'Copy' ? 'Copied!' : 'Copy'
            })
        });
</script>

which doesn't appear to be working correctly.

I have also tried modifying this solution to no avail. Is there an obvious reason why this isn't working?

Community
  • 1
  • 1

3 Answers3

4

You've set copyButton2 as the id of the element, yet you're using a class selector. You need to prefix the selector with #, not .

Also note that, depending on where you're running the jQuery code, you may also need to include a document.ready handler. Try this:

jQuery(function($) {
  $("#copyButton2").click(function() {
    $(this).text(function(i, v) {
      return v === 'Copy' ? 'Copied!' : 'Copy'
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="copyButton2">Copy</button>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

Please use id selector ("#copyButton2") instead of class selector as you have used id for the close button.

Ritwika Das
  • 189
  • 5
0

Here's a javascript solution while we're at it.

<script> 
  var testDiv = document.getElementById('test');

  testDiv.onclick = function(){
    testDiv.innerHTML = "Copied!"
  };
</script>
LJD
  • 498
  • 4
  • 11