user5887886
user5887886

Reputation:

Replace button text onclick JS

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?

Upvotes: 0

Views: 440

Answers (3)

LJD
LJD

Reputation: 496

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

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

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

Upvotes: 0

Ritwika Das
Ritwika Das

Reputation: 199

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

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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>

Upvotes: 4

Related Questions