user3353869
user3353869

Reputation:

How do I toggle a button text label in jQuery?

i made a button that hides some text, and it works good. but i want to change the text of the button from hide to show and so on, please help here's the code

<html>
<head>
<script src="jqueryLibrary.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle(1000);
    });
});
</script>
</head>
<body>
  <button>hide</button>
  <p>This is a paragraph with little content.</p>
  <p>This is another small paragraph.</p>
</body>
</html>

Upvotes: 0

Views: 64

Answers (2)

Chase W.
Chase W.

Reputation: 1413

If I understand correctly, you just want to change the button text?

<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle(1000);
   if($(this).html() == "Hide"){
      $(this).html("Hide");
   }
   else{
      $(this).html("Show");
   }
});
});
</script>

Upvotes: 1

Felix
Felix

Reputation: 38102

You can use text():

$(document).ready(function () {
    $("button").click(function () {
        $("p").toggle(1000);
        $(this).text(function(i, text){
            return text === "Show" ? "Hide" : "Show";
        })
    });
});

Fiddle Demo

Upvotes: 2

Related Questions