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?

1
  • 1
    use # for id . for class Commented May 11, 2017 at 12:55

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

5 Comments

This question must be close as a typo.
The selector typo may not be the only issue, as I stated in the answer the lack of a document.ready handler could be a factor too
Sorry, +1 instead :)
Typo was a rookie error on my behalf :/ and document handler also required - thanks Rory!
@JackVanstone no problem. Don't forget to accept an answer if it helped
0

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

Comments

0

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

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

  testDiv.onclick = function(){
    testDiv.innerHTML = "Copied!"
  };
</script>

1 Comment

This isn't quite the same. The OPs original toggles the value on successive clicks. This sets it to Copied! only

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.