Change button text on click using JavaScript
In this article, we are going to change the text of a button whenever it is clicked. I can't explain how easy it is! To change a button's text, we need to add a onclick event attribute to the button because whenever someone clicks the button we call a function.
- First, I have created a button element with onclick event attribute and I have passed a event object.
- I have created the function named myFunc().
- Inside this function, I have change the button's value using innerText property.
If you are thinking to use innerHTML property, then you can also use that. Basically, innerHTML property is used to change or add some html inside a particular element.
function myFunc(e){ e.innerHTML="<p style='color:#ff00ff'>Button Clicked</p>"; }Try it Yourself »
How to toggle text of s button.
Now you will learn how to toggle the value of a button using if-else statement. We can also use a switch statement instead of an if-else statement . But in this case, I will use if-else statement.
function myFunc(e){ if ( e.innerText == "click button" ){ e.innerText = "button clicked"; }else{ e.innerText = "click button"; } }Try it Yourself »
I want to show you one more easy example using toggle() method.
document.querySelector('.btn').addEventListener('click', function(e) { e.target.classList.toggle('new-class'); });Try it Yourself »
I hope you have learned how to change a button's text in this article. But what happens if there are a lot of buttons. Do you add click event to each button manually? You can write your answer in below comment section.
<input type="button" value="Show More" onclick="return change(this);" />
<script type="text/javascript">
function change(el){
if ( el.value === "Show More" ){
el.value = "Show Less";
}else{
el.value = "Show More";
}
}
</script>
https://www.3schools.in/p/embed.html?q=CjxidXR0b24gaWQ9InRvZ2dsZUJ1dHRvbiI+U2hvdyBBbnN3ZXI8L2J1dHRvbj4KPHAgaWQ9ImFuc3dlciIgaGlkZGVuPlRoaXMgaXMgdGhlIGFuc3dlciB5b3Ugd2FudCB0byBzaG93IGFuZCBoaWRlLjwvcD4KPHNjcmlwdD4KICBjb25zdCB0b2dnbGUgPSAoKSA9PiB7CiAgICBhbnN3ZXIuaGlkZGVuID0gIWFuc3dlci5oaWRkZW47CiAgICB0b2dnbGVCdXR0b24udGV4dENvbnRlbnQgPSBhbnN3ZXIuaGlkZGVuID8gIlNob3cgQW5zd2VyIiA6ICJIaWRlIEFuc3dlciI7CiAgfTsKCiAgY29uc3QgdG9nZ2xlQnV0dG9uID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoInRvZ2dsZUJ1dHRvbiIpOwogIGNvbnN0IGFuc3dlciA9IGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCJhbnN3ZXIiKTsKICAKICB0b2dnbGVCdXR0b24uYWRkRXZlbnRMaXN0ZW5lcigiY2xpY2siLCB0b2dnbGUpOwo8L3NjcmlwdD4=