user2983258
user2983258

Reputation: 161

toggle text of button with jquery

<button class="btn hide_show">Don't show text</button>

$(".hide_show").toggle(function () {
    $(this).text("Show text");
}, function () {
    $(this).text("Don't show text");
});

http://jsfiddle.net/x83qg/1/

I don't know exactly why this code doesn't work. The idea is toggle the text of the button

Upvotes: 1

Views: 54

Answers (3)

nnnnnn
nnnnnn

Reputation: 150010

jQuery originally had two .toggle() functions. One toggles visibility, and the other sets up a click handler that toggles between multiple handlers. Which function was used depended on what arguments were passed in. It seems to be the latter that you are trying to use, but it was deprecated in v1.8 and removed in v1.9.

Fortunately it's pretty easy to implement something like the removed .toggle():

var text = ["Show text", "Don't show text"],
    i = 0;
$(".hide_show").click(function () {
    $(this).text(text[i]);
    i = (i + 1) % text.length;
});

Demo: http://jsfiddle.net/x83qg/12/

Note that (like the old .toggle() function that allowed more than two handlers) the code I've shown will cycle through all items in the array, so you're not restricted to just switching back and forth between only two items.

Upvotes: 1

codingrose
codingrose

Reputation: 15699

Try:

var txt = $(".hide_show").text().toLowerCase();
if(txt == "show text"){
    $(".hide_show").text("Don't show text");
}
else{
    $(".hide_show").text("Show text");
}

DEMO here

Upvotes: 0

Adil
Adil

Reputation: 148110

The toggle function you have executes on DOM ready and hides the button and there is no way to show it again. You probably need to change the text of click.

Live Demo

$(".hide_show").click(function () {
   $(this).text( $(this).text() == "Show text" ? "Don't show text" :"Show text");
});

Upvotes: 2

Related Questions