72

When i click ".pushme" button, it turns its text to "Don't push me". I want to turn the text again to "push me" when button is clicked again. How can i do that?

<html>

<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<body>
    <button class='pushme'>PUSH ME</button>
    <script>
        $(".pushme").click(function () {
            $(this).text("DON'T PUSH ME");
        });
    </script>
</body>

</html>

http://jsfiddle.net/DQK4v/

Thanks.

1
  • possible duplicate of Jquery Toggle Text? Commented Mar 2, 2014 at 8:40

10 Answers 10

218

You can use text method:

$(function(){
   $(".pushme").click(function () {
      $(this).text(function(i, text){
          return text === "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME";
      })
   });
})

http://jsfiddle.net/CBajb/

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

6 Comments

Can someone explain why having specific html inside the html function will not work? jsfiddle.net/CBajb/18
if PUSH ME and DON'T PUSH ME are actually two paragraphs, then is there a cleaner way to do this?
Yes, there is. Use an object: conditon ? obj.par1 : obj.par2. Another option is toggling the visibility of the elements.
@undefined what is the point of the parameter "i"? I don't understand why it is needed but I know that it is needed since it does not work without it. I understand why text is needed but "i" is not used at all?
@gmonz i refers the index of iteration. We have to accept the first parameter for using the second parameter. That's how functions work! One can also use this.textContent instead of the second parameter of the callback function. Basically text here is equal to this.currentText, where this refers to a clicked .pushme element.
|
21

You could also use .toggle() like so:

$(".pushme").toggle(function() {
    $(this).text("DON'T PUSH ME");
}, function() {
    $(this).text("PUSH ME");
});

More info at http://api.jquery.com/toggle-event/.

This way also makes it pretty easy to change the text or add more than just 2 differing states.

3 Comments

.toggle has been removed as of jquery 1.9. That's a shame. Looks quite nice!
@Relequestual It's true, unfortunately. Toggle still exists for hiding/showing elements api.jquery.com/toggle but this example would no longer work post 1.9. :(
@Relequestual There are pretty good alternatives, see, for example, this answer.
16

Use a custom ID if possible if you would like to apply the action to only that button.

HTML

<button class="pushDontpush">PUSH ME</button>

jQuery

$("#pushDontpush").click(function() { 
    if ($(this).text() == "PUSH ME") { 
        $(this).text("DON'T PUSH ME"); 
    } else { 
        $(this).text("PUSH ME"); 
    }; 
});

Working CodePen: Toggle text in button

Comments

8

Use an if/else statement.. or ternary if you understand it

$(".pushme").click(function () {
    var $el = $(this);
    $el.text($el.text() == "DON'T PUSH ME" ? "PUSH ME": "DON'T PUSH ME");
});

http://jsfiddle.net/dFZyv/

Comments

6

With so many great answers, I thought I would toss one more into the mix. This one, unlike the others, would permit you to cycle through any number of messages with ease:

var index = 0,
    messg = [
        "PUSH ME", 
        "DON'T PUSH ME", 
        "I'M SO CONFUSED!"
    ];

$(".pushme").on("click", function() {
    $(this).text(function(index, text){
        index = $.inArray(text, messg);
        return messg[++index % messg.length];
    });
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​);​

Demo: http://jsfiddle.net/DQK4v/2/

Comments

5
$(".pushme").click(function () {
  var button = $(this);
  button.text(button.text() == "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME")           
});

This ternary operator has an implicit return. If the expression before ? is true it returns "DON'T PUSH ME", else returns "PUSH ME"

This if-else statement:

if (condition) { return A }
else { return B }

has the equivalent ternary expression:

condition ? A : B

Comments

4

I preffer the following way, it can be used by any button.

<button class='pushme' data-default-text="PUSH ME" data-new-text="DON'T PUSH ME">PUSH ME</button>

$(".pushme").click(function () {
    var $element = $(this);
    $element.text(function(i, text) {
        return text == $element.data('default-text') ? $element.data('new-text')
                                                     : $element.data('default-text');
    });
});

demo

Comments

3

If you're setting the button text by using the 'value' attribute you'll need to set

  • $(this).val()

instead of:

  • $(this).text()

Also in my situation it worked better to add the JQuery direct to the onclick event of the button:

onclick="$(this).val(function (i, text) { return text == 'PUSH ME' ? 'DON'T PUSH ME' : 'PUSH ME'; });"

2 Comments

For me, this is only working every other button click.
A friend helped me figure out that it was because I had two event listeners. I was just pasting code from the other answer straight into a JS file, and I was calling the parent function from an onclick as well.
2

You can also use math function to do this

var i = 0;
$('#button').on('click', function() {
    if (i++ % 2 == 0) {
        $(this).val("Push me!");
    } else {
        $(this).val("Don't push me!");
    }
});

DEMO

Comments

1

Instead of incrementing the above example to infinity, you can use a simpler solution:

var i=0;
      $('#button').on('click', function() {
          if(i == 0){
            $(this).val("Don't push me!"); i = 1;
          }else{
            $(this).val("Push me!"); i = 0;
          }
      });

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.