jQuery Form How to - Change button text when button clicked








Question

We would like to know how to change button text when button clicked.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.10.1.js'></script>
<style type='text/css'>
.bodyRed {<!--  w  ww .j av  a2s. c o m-->
  background-color: red;
}
</style>
<script type='text/javascript'>
$(function(){
    var $body = $('body'),
        $button = $('#lumiere');

    $button.on('click', function(event) {
        if($body.hasClass('bodyRed')) {
            $body.removeClass('bodyRed');
            $button.text('2');
        } else {
            $body.addClass('bodyRed');
            $button.text('1');
        }
    });
});
</script>
</head>
<body>
  <button id="lumiere">1</button>
</body>
</html>

The code above is rendered as follows: