How to change text within a button on click in Jquery

How to change text within a button on click in Jquery

Posted by Luke Beeno on August 14, 2022

How to change text within a button on click in Jquery

How to change text within a button on click in Jquery

Posted by Luke Beeno on August 14, 2022

To change a button on click in Jquery:

Step 1. Get the specified botton field by using selector $("#id")

Step 2. Add on click event to button

Step 3. Use text() method to change text 

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wecode101 change text within button Jquery</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
          <button type="text" class="btn btn-primary" id="btn">Open</button>
        </div>
    </div>
</body>
</html>

JS

$( "#btn" ).click(function(){
    $("#btn").text("close");
});

Or

$( "#btn" ).click(function(){
    $("#btn").html('close');
});