0

Recently, jQuery removed .toggle(), and I don't know how to toggle text within a button. And yes, I've looked around this forum for an answer, but none were adequate.

Here is my code:

$("#show").click(function () {
if($(this).text() == "Show") {
    $(this).text() == "Hide";
    alert("Fill fields");
} else {
    $(this).text() == "Show";
    alert("Clear fields");
}
});

Explanation:

  • When #show is clicked, execute anonymous function.
  • if the text is "Show", change to "Hide"
  • then, alert "Fill fields"
  • Else, change text to "show"
  • alert "Clear fields"

fiddle.

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
Matthew
  • 2,158
  • 7
  • 30
  • 52
  • `$(this).text() == "Hide";` is checking for equality. It shoudl be `$(this).text("Hide");` – karthikr Jul 04 '14 at 02:25
  • I have rolled back your edit, because an edit should not change the meaning of a question. – Sumurai8 Jul 04 '14 at 07:25
  • possible duplicate of [What is alternative to use after jQuery 1.9 removed .toggle(function,function)?](http://stackoverflow.com/questions/14490957/what-is-alternative-to-use-after-jquery-1-9-removed-togglefunction-function) – Ryan McDonough Jul 04 '14 at 08:29

3 Answers3

3

The setter of .text() is like this:

$(selector).text('text here') // this is setter

and not

$(selector).text() == 'text here'; // this is comparison

So full code:

$("#show").click(function () {
    if($(this).text() == "Show") {
        $(this).text("Hide");
        alert("Fill fields");
    } else {
        $(this).text("Show");
        alert("Clear fields");
    }
});

DEMO

You can shorten it with ternary operators if you want to:

$('#show').click(function(){
   $(this).text(function(_, text) { return text == 'Show' ? 'Hide' : 'Show'; });    
});
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

Quite likely you were looking for toggle event alternative; you could pass n functions to it and they would be fired in succession as you clicked.

Check jquery-toggleclick.js. toggleClick jQuery plugin will do just that.

Usage:

$("#show").toggleClick(fillFields, clearFields);

Then you can set the text in the appropriate function

Amit Kumar Gupta
  • 7,193
  • 12
  • 64
  • 90
PeterKA
  • 24,158
  • 5
  • 26
  • 48
-3

I checked jquery documentation. Toggle is still there. http://api.jquery.com/toggle/