Change button text with jQuery

Its essential to change t he button text in some applications . For example Like button. If the current is “Like”, after click on the button it the button text will be “Liked”

jquery makes process efficient.


<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<button class="like-button">Like</button>

<script>
$(document).ready(function(){
    $('.like-button').click(function(){
        var buttonText = $(this).text();
        if (buttonText === 'Like') {
            $(this).text('Liked');
        } else {
            $(this).text('Like');
        }
    });
});
</script>

</body>
</html>



The same example without jquery


<!DOCTYPE html>
<html>
<head>
</head>

<body>
<button class="like-button" onclick="toggleLike(this)">Like</button>

<script>
function toggleLike(button) {
    if (button.textContent === 'Like') {
        button.textContent = 'Liked';
    } else {
        button.textContent = 'Like';
    }
}
</script>

</body>
</html>



Copy and run the html code directly here

Related Posts

How to HTML open link in new in tab in browser
July 3, 2024

We can add this target=”_blank” in the <a> tag to open link in new tab Example code <!DOCTYPE html> <head> </head> <body> &lt!– Opens in the same tab –> <a href=”https://en.wikipedia.org/wiki/Main_Page”>Visit Wikipedia (same tab)</a> <br> &lt!– Opens in a new tab –> <a href=”https://en.wikipedia.org/wiki/Main_Page” target=”_blank”>Visit Wikipedia (new tab)</a> </body> </html> Copy Code

How to prevent text selection in html
April 28, 2024

Its necessary to prevent text selection when the text is ui feature, to make the webpage more professional. We can prevent the text from selecting by using this in css You cannot select this text You can select this text example code

How to create tooltip in html
April 28, 2024

Is essential to add tooltip to make web page more professional and understandable The simplest way can we add tooltip is use html inline element <span> We will add the tool in div and tooltip text(tool description) in the span Toll description will be always hide ( display none in css) until the user hover […]