Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change my button text onclick?

I have a jQuery slideToggle that I am using to display and hide certain content. It always show an arrow pointing down, but if clicked and the text is shown, the arrow should be pointing up. Anyway to do this?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("p").slideToggle();
        });
    });
</script>

<button>&#8595;</button>
<p>Wow!</p>

</body>
</html>
like image 603
Lucafraser Avatar asked Mar 31 '16 06:03

Lucafraser


4 Answers

As simple as that!

var toggled = false;
$("button").click(function() {
  if (!toggled) {
    $(this).html("&#8593;");
    toggled = true;
  } else {
    $(this).html("&#8595;");
    toggled = false;
  }

  $("p").slideToggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
  &#8595;
</button>
<p>
  Wow!
</p>
like image 108
Jorrex Avatar answered Oct 18 '22 21:10

Jorrex


Working Demo

$(document).ready(function() {
  $("button").click(function() {
    $("p").slideToggle();
    $(this).toggleClass('down up');

  });
});
.down {
  background-image: url("https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_down_48px-128.png");
  height: 130px;
  width: 130px;
}
.up {
  background-image: url("https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_up_48px-128.png");
  height: 130px;
  width: 130px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="down"></button>
<p>Wow!</p>
like image 27
Rino Raj Avatar answered Oct 18 '22 20:10

Rino Raj


Try something like this.. :)

$(document).ready(function(){
    $("button").click(function(){
        $("p").slideToggle();
        $( this ).text('NewButtonText');
    });
});
like image 2
Oscar K Avatar answered Oct 18 '22 22:10

Oscar K


This solutions checks if the button has an arrow pointing 'UP', if it does, replaces it with 'DOWN', and vice versa.

    $(document).ready(function(){
        $("button").click(function(){
            if ($(this).text() == 'up'){
                $(this).html('&#8595;')
            }else{
                $(this).html('up');
            }
            $("p").slideToggle();
        });
    });

https://jsfiddle.net/gogaa33d/

like image 2
Unamata Sanatarai Avatar answered Oct 18 '22 20:10

Unamata Sanatarai