jQuery Change Button Text Value Dynamically.

/ / 1 Comments

jQuery Change text dynamically: This article explains how on button click we can change text value of that clicked button  .i.e dynamic button text value gets changed. For example, when we have buttons like Follow, Like, Pending, etc. and on click we need to change its text as Unfollow, Unlike, Complete. So here with jQuery, we can easily modify the button text based on some condition. In jQuery we use .val() method for changing the text of  button, and if the button is div tag then for div tag we have to change its text then we use .text() method.

HTML:

Add a button tag, and on button click will amend its text.
//*
<input id="myBtn" type="button" value="Show" />
//*
 jQuery: JS code to change button text.
$("#myBtn").on('click',function(){
    var self=$(this);
    if(self.val()=="Show")     {
   	 self.val("Hide");  
    }
    else {
   	 self.val("Show");
    }
});

Explanation:

Here in the above code myBtn is the button id. And on click() event we check its value and according to the current text we change our button text. In real development on button click jquery ajax function gets call and based on its response the button text gets changed.

As keeping this article as simple, we are not going to make any ajax call, instead, we just checked the current text and changed based on it. You might have noticed here in above jQuery code variable self is used this is called caching variable good (practise performance wise).


Same we change text Follow to Unfollow in jQuery as written below:

$("#myFollowButton").on('click',function(){
    var self=$(this);
    if(self.val()=="Follow")     {
   	 self.val("Unfollow");  
    }
    else {
   	 self.val("Follow");
    }
});

Conclusion: Here in this article we learn how in jQuery change text dynamically can be done. By using val() we convert Follow button into Unfollow button.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

1 Comments