admin管理员组

文章数量:1325408

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

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

Share Improve this question asked Oct 30, 2012 at 21:50 user1246462user1246462 1,2783 gold badges11 silver badges21 bronze badges 3
  • What actually have you tried? – zerkms Commented Oct 30, 2012 at 21:53
  • Both the answers have the text toggling after clicking it twice. I would like the text to toggle after clicking it immediately, is there a way that can happen? – user1246462 Commented Oct 31, 2012 at 23:40
  • have you ever done your work yourself? – zerkms Commented Oct 31, 2012 at 23:45
Add a ment  | 

2 Answers 2

Reset to default 6

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');
    }
});

Following your DOM tree

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

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

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

});

本文标签: javascriptToggling button text in jqueryStack Overflow