user1246462
user1246462

Reputation: 1278

Toggling button text in jquery

I have an HTML button created and I want to toggle the text that is displayed in the button between two text using Javascript/JQuery. How do I do this?

Currently, I have:

<button onclick="showAll();" class="collapse-classes">
    <span class="button-text">Show</span>
</button>

The button starts off by displaying "Show" and then switch to "Hide" when clicked and then switch to "Show" when clicked again and onward. I tried changing the value of the tag but it doesn't change the text displayed. Can anyone help with the script? thanks

Upvotes: 2

Views: 9175

Answers (2)

Joao Almeida
Joao Almeida

Reputation: 982

Following your DOM tree

$('.collapse-classes').click(function() {

    var span = $(this).find('span');

    if(span.text() == "Show"){
        span.text("Hide");
    } else {
        span.text("Show");
    }

});

Upvotes: 0

Blender
Blender

Reputation: 298176

Don't use onclick. Just bind an event handler.

Here's something you can work with:

$('.collapse-classes').click(function() {
    var $this = $(this);

    $this.toggleClass('show');

    if ($this.hasClass('show')) {
        $this.text('Show');
    } else {
        $this.text('Hide');
    }
});

Upvotes: 6

Related Questions