71

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.

Dorukcan Kişin
  • 1,121
  • 2
  • 14
  • 29
  • possible duplicate of [Jquery Toggle Text?](http://stackoverflow.com/questions/2155453/jquery-toggle-text) – user Mar 02 '14 at 08:40

10 Answers10

214

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/

Ram
  • 143,282
  • 16
  • 168
  • 197
  • 1
    Can someone explain why having specific html inside the ``html`` function will not work? http://jsfiddle.net/CBajb/18/ – user1429980 Sep 27 '13 at 05:20
  • 1
    if `PUSH ME` and `DON'T PUSH ME` are actually two paragraphs, then is there a cleaner way to do this? – Ooker Aug 06 '16 at 05:42
  • 1
    Yes, there is. Use an object: `conditon ? obj.par1 : obj.par2`. Another option is toggling the visibility of the elements. – Ram Aug 06 '16 at 12:05
  • 1
    @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 Jun 04 '17 at 03:07
  • 3
    @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. – Ram Jun 06 '17 at 00:10
  • without jQuery in the HTML you can do: `` – ManInTheArena Jan 11 '20 at 22:33
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.

JGallardo
  • 11,074
  • 10
  • 82
  • 96
gotohales
  • 3,665
  • 1
  • 20
  • 34
  • 2
    .toggle has been removed as of jquery 1.9. That's a shame. Looks quite nice! – Relequestual Jun 18 '13 at 09:18
  • 4
    @Relequestual It's true, unfortunately. Toggle still exists for hiding/showing elements http://api.jquery.com/toggle/ but this example would no longer work post 1.9. :( – gotohales Jun 18 '13 at 15:59
  • 1
    @Relequestual There are pretty good alternatives, see, for example, [this answer](http://stackoverflow.com/questions/2155453/jquery-toggle-text#17452139). – user Mar 02 '14 at 08:39
15

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

JGallardo
  • 11,074
  • 10
  • 82
  • 96
timbck2
  • 1,036
  • 3
  • 15
  • 36
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/

wirey00
  • 33,517
  • 7
  • 54
  • 65
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/

Sampson
  • 265,109
  • 74
  • 539
  • 565
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
Art Knipe
  • 99
  • 1
  • 6
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

Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82
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'; });"
Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
  • For me, this is only working every other button click. – Brent Connor Sep 03 '15 at 18:01
  • 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. – Brent Connor Sep 03 '15 at 18:14
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

JSEvgeny
  • 2,550
  • 1
  • 24
  • 38
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;
          }
      });
user1286956
  • 277
  • 3
  • 19