1

I've found part of my answer on :jQuery change button text

to change the text of a button on the click. What I'm searching for is how to toggle that text. I've tried using the class method to toggle the text of "show teams" / "hide teams". If I just use the property I can change the text on the button click but that will not change it back.

HTML

<input class="teams" type="button" value="Teams" />

js

    $(".teams").click(function () {
        $("#container2").toggle();
        //$("#teams").prop("value", "Hide Teams");

        var $this = $(this);
        if ($this.hasClass('teams')) {
            $this.text('Show Teams');
        } else {
            $this.text('Hide Teams');
        }
    });
Community
  • 1
  • 1
Troy Bryant
  • 994
  • 8
  • 29
  • 60

3 Answers3

2

input elements do not have text content

Quoting the jQuery docs

Get the combined text contents of each element in the set of matched elements, including their descendants.


Either use a button tag

<button class="teams">Teams</button>

or use the .val() method (that applies to input elements) instead of the .text()

Now since you test for the existence of the teams class you will need to also toggle that

    var $this = $(this);
    if ($this.hasClass('teams')) {
        $this.text('Show Teams');
    } else {
        $this.text('Hide Teams');
    }
    $this.toggleClass('teams'); // add this line
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1
    $(".teams").click(function () {
        $("#container2").toggle();
        //$("#teams").prop("value", "Hide Teams");

        var $this = $(this);
        if ($this.val() === 'Show Teams') {
            $this.val('Hide Teams');
        } else {
            $this.val('Show Teams');
        }
    });
j08691
  • 204,283
  • 31
  • 260
  • 272
Sam
  • 15,336
  • 25
  • 85
  • 148
0

You'll want to set the attribute value to your text: $this.attr('value', 'Show Teams');

JSFiddle:

http://jsfiddle.net/qMrbn/

egl
  • 167
  • 1
  • 1
  • 8