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

If you get a task to change the text of a button after being clicked. You can use jquery to acheive it. 

Let us just get right into how this can be achieved. 

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() or html() 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");
});

The text() gets the contents of the button element by identifying it using the id selector.

If the text in the button is numeric or boolean it will be converted to a string representation.

Or

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

The html() does the same as the text(), the only difference is the text() can be used in XML as well as HTML files.

Any question?
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question