When I click on myButton1 button, I want the value to change to Close Curtain from Open Curtain.
HTML:
<input onclick="change()" type="button" value="Open Curtain" id="myButton1"></input>
Javascript:
function change();
{
document.getElementById("myButton1").value="Close Curtain";
}
The button is displaying open curtain right now and I want it to change to close curtain, is this correct?
Rex5
7718 silver badges23 bronze badges
asked May 20, 2012 at 6:02
0
If I’ve understood your question correctly, you want to toggle between ‘Open Curtain’ and ‘Close Curtain’ — changing to the ‘open curtain’ if it’s closed or vice versa. If that’s what you need this will work.
function change() // no ';' here
{
if (this.value=="Close Curtain") this.value = "Open Curtain";
else this.value = "Close Curtain";
}
Note that you don’t need to use document.getElementById("myButton1") inside change as it is called in the context of myButton1 — what I mean by context you’ll come to know later, on reading books about JS.
UPDATE:
I was wrong. Not as I said earlier, this won’t refer to the element itself. You can use this:
function change() // no ';' here
{
var elem = document.getElementById("myButton1");
if (elem.value=="Close Curtain") elem.value = "Open Curtain";
else elem.value = "Close Curtain";
}
answered May 20, 2012 at 6:08
Parth ThakkarParth Thakkar
5,3973 gold badges25 silver badges34 bronze badges
7
When using the <button> element (or maybe others?) setting ‘value’ will not change the text, but innerHTML will.
var btn = document.getElementById("mybtn");
btn.value = 'my value'; // will just add a hidden value
btn.innerHTML = 'my text';
When printed to the console:
<button id="mybtn" class="btn btn-primary" onclick="confirm()" value="my value">my text</button>
answered Feb 27, 2018 at 9:49
Baked InhalfBaked Inhalf
3,2151 gold badge29 silver badges43 bronze badges
1
It seems like there is just a simple typo error:
- Remove the semicolon after change(), there should not be any in the
function declaration. - Add a quote in front of the myButton1 declaration.
Corrected code:
<input onclick="change()" type="button" value="Open Curtain" id="myButton1" />
...
function change()
{
document.getElementById("myButton1").value="Close Curtain";
}
A faster and simpler solution would be to include the code in your button and use the keyword this to access the button.
<input onclick="this.value='Close Curtain'" type="button" value="Open Curtain" id="myButton1" />
answered May 20, 2012 at 6:25
There are lots of ways. And this should work too in all browsers and you don’t have to use document.getElementById anymore since you’re passing the element itself to the function.
<input type="button" value="Open Curtain" onclick="return change(this);" />
<script type="text/javascript">
function change( el )
{
if ( el.value === "Open Curtain" )
el.value = "Close Curtain";
else
el.value = "Open Curtain";
}
</script>
answered May 20, 2012 at 7:26
this code work for me
var btn = document.getElementById("your_btn_id");
if(btn.innerText=="show"){
btn.innerText="hide";
}
else{
btn.innerText="show";
}
using value is not work in my case
answered Apr 13, 2020 at 8:21
Add this function to the script
function myFunction() {
var btn = document.getElementById("myButton");
if (btn.value == "Open Curtain") {
btn.value = "Close Curtain";
btn.innerHTML = "Close Curtain";
}
else {
btn.value = "Open Curtain";
btn.innerHTML = "Open Curtain";
}
}
and edit the button
<button onclick="myFunction()" id="myButton" value="Open Curtain">Open Curtain</button>
answered Dec 13, 2018 at 10:30
Krisi SuciKrisi Suci
1291 silver badge4 bronze badges
If you prefer binding your events outside the html-markup (in the javascript) you could do it like this:
document.getElementById("curtainInput").addEventListener(
"click",
function(event) {
if (event.target.value === "Open Curtain") {
event.target.value = "Close Curtain";
} else {
event.target.value = "Open Curtain";
}
},
false
);
<!doctype html>
<html>
<body>
<input
id="curtainInput"
type="button"
value="Open Curtain" />
</body>
</html>
answered Sep 5, 2018 at 7:15
PålOliverPålOliver
2,3831 gold badge22 silver badges24 bronze badges
i know this is an old post but there is an option to sent the elemd id with the function call:
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
<button id='expand' class='btn expand' onclick='f1(this)'>Expand</button>
function f1(objButton)
{
if (objButton.innerHTML=="EXPAND") objButton.innerHTML = "MINIMIZE";
else objButton.innerHTML = "EXPAND";
}
answered Nov 12, 2020 at 12:42
You are missing an opening quote on the id= and you have a semi-colon after the function declaration. Also, the input tag does not need a closing tag.
This works:
<input onclick="change()" type="button" value="Open Curtain" id="myButton1">
<script type="text/javascript">
function change()
{
document.getElementById("myButton1").value="Close Curtain";
}
</script>
answered May 20, 2012 at 6:08
Sp4cecatSp4cecat
9911 gold badge8 silver badges18 bronze badges
Try this,
<input type="button" id="myButton1" value="Open Curtain" onClick="javascript:change(this);"></input>
<script>
function change(ref) {
ref.value="Close Curtain";
}
</script>
answered May 20, 2012 at 6:26
premnathcspremnathcs
5453 silver badges11 bronze badges
1
this can be done easily with a vbs code (as i’m not so familiar with js )
<input type="button" id="btn" Value="Close" onclick="check">
<script Language="VBScript">
sub check
if btn.Value="Close" then btn.Value="Open"
end sub
</script>
and you’re done , however this changes the Name to display only and does not change the function {onclick} , i did some researches on how to do the second one and seem there isnt’ something like
btn.onclick = ".."
but i figured out a way using <«span»> tag it goes like this :
<script Language="VBScript">
Sub function1
MsgBox "function1"
span.InnerHTML= "<Input type=""button"" Value=""button2"" onclick=""function2"">"
End Sub
Sub function2
MsgBox "function2"
span.InnerHTML = "<Input type=""button"" Value=""button1"" onclick=""function1"">"
End Sub
</script>
<body>
<span id="span" name="span" >
<input type="button" Value="button1" onclick="function1">
</span>
</body>
try it yourself , change the codes in sub function1 and sub function2, basically all you need to know to make it in jscript is the line
span.InnerHTML = "..."
the rest is your code you wanna execute
hope this helps 
answered Apr 10, 2015 at 11:40
1
This worked fine for me. I had multiple buttons which I wanted to toggle the input value text from ‘Add Range’ to ‘Remove Range’
<input type="button" onclick="if(this.value=='Add Range') { this.value='Remove Range'; } else { this.value='Add Range'; }" />
answered Sep 27, 2018 at 0:59
var count=0;
document.getElementById("play").onclick = function(){
if(count%2 =="1"){
document.getElementById("video").pause();
document.getElementById("play").innerHTML ="Pause";
}else {
document.getElementById("video").play();
document.getElementById("play").innerHTML ="Play";
}
++count;
answered May 16, 2019 at 14:43
This is simple way to change Submit to loading state
<button id="custSub" type="submit" class="button left tiny" data-text-swap="Processing.. ">Submit <i class="fa fa-angle-double-right"></i></button>
<script>
jQuery(document).ready(function ($) {
$("button").on("click", function() {
var el = $(this);
if (el.html() == el.data("text-swap")) {
el.html(el.data("text-original"));
} else {
el.data("text-original", el.html());
el.html(el.data("text-swap"));
}
setTimeout(function () {
el.html(el.data("text-original"));
}, 500);
});
});
</script>
answered Jul 2, 2014 at 9:06
<input type="button" class="btn btn-default" value="click me changtext" id="myButton1" onClick="changetext()" >
<script>
function changetext() {
var elem = document.getElementById("myButton1");
if (elem.value=="click me change text")
{
elem.value = "changed text here";
}
else
{
elem.value = "click me change text";
}
}
</script>
answered Nov 10, 2014 at 7:44
If not opposed to or may already be using jQuery, you could do this without the approach of having to use obtrusive js. Hope it helps. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript Also like to reference, https://stackoverflow.com/a/3910750/4812515 for a discussion on this.
HTML:
<input type="button" value="Open Curtain" id=myButton1"></input>
Javascript:
$('#myButton1').click(function() {
var self = this;
change(self);
});
function change( el ) {
if ( el.value === "Open Curtain" )
el.value = "Close Curtain";
else
el.value = "Open Curtain";
}
answered Sep 2, 2015 at 22:17
alphapilgrimalphapilgrim
3,6588 gold badges28 silver badges57 bronze badges
<!DOCTYPE html>
<html>
<head>
<title>events2</title>
</head>
<body>
<script>
function fun() {
document.getElementById("but").value = "onclickIChange";
}
</script>
<form>
<input type="button" value="Button" onclick="fun()" id="but" name="but">
</form>
</body>
</html>
Jozef Dúc
9652 gold badges18 silver badges29 bronze badges
answered Oct 19, 2017 at 11:41
kaustubhd9kaustubhd9
1011 silver badge6 bronze badges
Or more simple without having to name the element (with ‘button’ element):
<button onclick="toggleLog(this)">Stop logs</button>
and script :
var bWriteLog = true;
function toggleLog(elt) {
bWriteLog = !bWriteLog;
elt.innerHTML = bWriteLog ? 'Stop logs' : 'Watch logs';
}
answered Apr 8, 2019 at 15:11
function change() {
myButton1.value=="Open Curtain" ? myButton1.value="Close Curtain" : myButton1.value="Open Curtain";
}
answered Feb 5, 2021 at 14:29
Richard ZRichard Z
1512 silver badges3 bronze badges
1
На shpargalkablog.ru уже был показан скрипт меняющегося текста на jQuery. Теперь рассмотрим варианты, где смена происходит по щелчку мышки.
Самый простой вариант
<input type="button" value="Щелчок" onclick="this.value='Скрипт сработал'">
После щелчка кнопка перестаёт быть активной
<input type="button" value="Щелчок" onclick="this.disabled=1; this.value='Скрипт сработал'; ">
Поменять ссылку
<script type="text/javascript">
function changeLink()
{
document.getElementById('myAnchor').innerHTML="Скрипт Упорядочить таблицу";
document.getElementById('myAnchor').href="http://shpargalkablog.ru/2011/07/uporyadochet-tablitsu-po-alfavitu.html";
document.getElementById('myAnchor').target="_blank";
}
</script>
<a id="myAnchor" href="http://shpargalkablog.ru/2010/11/poyavlyayushchiesya-commentarii.html">Скрипт "Показать скрыть текст"</a>
<input type="button" onclick="changeLink()" value="Change link">
Скрипт «Показать скрыть текст»
Заменить кнопку на ссылку
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Текст изменился';
}
</script>
<a id='boldStuff' href="#" onclick="changeText();return false;">Нажать</a>
Нажать
Смена на текст, заполненный в окне
<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
}
</script>
<p>
Поменяем текст на введённый в форму ниже <b id='boldStuff2'>а именно на</b> </p>
<input type='text' id='userInput' value=' Введите вашу фразу ' /><input type='button' onclick='changeText2()' value='Change Text'/>
Поменяем текст на введённый в форму ниже а именно на
Выбор из меню
<script language="javascript">
var selected_state;
function ckswapText(obj)
{
selected_state = obj.value;
if(selected_state == "")
return;
if(selected_state =="AZ")
changeText();
else if( selected_state =="CA")
swapText3();
else if( selected_state == "CO")
swapText4();
else
olswapText();
}
function changeText(){
document.getElementById('boldStuff').innerHTML = 'порода собак';
}
function swapText3(){
document.getElementById('boldStuff').innerHTML = 'порода кошек';
}
function swapText4(){
document.getElementById('boldStuff').innerHTML = 'порода кроликов';
}
function olswapText(){
document.getElementById('boldStuff').innerHTML = 'порода лошадей';
}
</script>
<select class="apply_text" size="1" name="billto_state" id="billto_state" onchange="ckswapText(this);">
<option value="" selected>Алабай</option>
<option value="AL">Буденновская порода</option>
<option value="AK">Алтайская порода</option>
<option value="AZ">Австралийская овчарка</option>
<option value="AR">Австралийский Пони</option>
<option value="CA">Турецкая ангора</option>
<option value="CO">Огневка</option>
<option value="WY">Бурятская порода</option>
</select>
<p>
Это <b id='boldStuff'>порода собак</b> </p>
Поменять два раза туда и обратно
<script type='text/JavaScript'>
function verocultar(cual) {
var c=cual.nextSibling;
if(c.innerHTML=='сказ два') {
c.innerHTML='сказ раз';
} else {
c.innerHTML='сказ два';
}
return false;
}
</script><a onclick="return verocultar(this);"
href="javascript:void(0);">замена</a><div>
....... содержание .......
</div>
замена……. содержание …….
Добавить текст в textarea
<textarea id="text">строка</textarea>
<script language="javascript" type="text/javascript">
var text=document.getElementById("text");
text.value="<b>"+text.value+"</b>";
</script>
Добавить текст в textarea по щелчку
<script type="text/javascript">
function changeLink()
{
var text=document.getElementById("myAnchor");
document.getElementById('myAnchor').value="<b>"+text.value+"</b>";
}
</script>
<input type="text" id="myAnchor" value="значение"/>
<input type="button" onclick="changeLink()" value="Change link">
Выделение части текста в textarea
<textarea id="textarea">Какой-то текст. Если его часть выделить и нажать на кнопку, то этот текст будет окружён тегами b</textarea>
<br />
<button type="button" id="button">кнопка</button>
<script>
var textarea = document.getElementById("textarea");
var button = document.getElementById("button");
button.onclick = function() {
var len = textarea.value.length,
start = textarea.selectionStart,
end = textarea.selectionEnd,
sel = textarea.value.substring(start, end),
replace = '<b>' + sel + '<b>';
textarea.value = textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);
}
</script>
Дополнительные ссылки: developer.mozilla.org с примером, corpocrat.com с вариантом для старых IE
Заменить символ с помощью скрипта
<script type="text/javascript">
function decode() {
var obj = document.getElementById('dencoder');
var encoded = obj.value;
obj.value = decodeURIComponent(encoded.replace(/</g, "〈"));
var encoded1 = obj.value;
obj.value = decodeURIComponent(encoded1.replace(/>/g, "〉"));
}
</script><form onsubmit="return false;">
<textarea id="dencoder" rows="1" cols="50"><b>строка1</b></textarea><input type="button" value="Decode" onclick="decode()"/>
</form>
или
<script> document.documentElement.innerHTML = document.documentElement.innerHTML.replace(/858/g, "505"); </script>
Зачем всё это
Привет, друзья. Вопрос был от читателя, как сделать смену текста на
странице, когда при нажатие на кнопку один текст меняется на другой и обратно. Вариант достаточно распространённый и, часто
встречающийся. Покажу несколько вариантов, как по клику быстро сменить текст
на другой .
Первые 2 будут просто менять текст, не возвращая прежний. Все пробуем в этом редакторе для наглядности. Копируйте код и вставляем в поле для просмотра.
1.
Вариант. Использовать подготовленный текст, кнопку, с помощью которой
будет осуществляться замена, и скрипт JS.
<p class=»par»>Здесь ваш тестовый текст</p>
<button onclick=»fu()» type=»text»>Нажми на меня и посмотри
.</button>
<script>
function fu(){
var par = document.querySelector(‘.par’);
par.innerHTML = ‘Получилось!!!! УРА, УРА, УРА’;
}
</script>
2. Вариант. Смена текущего текст без кнопки.
<h1 onclick=»changeText(this)»>Попробуй кликнуть на меня!</h1>
<script>
function changeText(id) {
id.innerHTML = «Получилось ! УРА, УРА, УРА»;
}
</script>
3. Вариант. Как заменить содержимое блока на другое при клике, а при
повторном, обратно.
<script type=’text/JavaScript’>
function verocultar(cual) {
var c=cual.nextSibling;
if(c.innerHTML==’второй текст второй
текст’) {
c.innerHTML=’первый
текст первый текст’;
} else {
c.innerHTML=’второй
текст второй текст’;
}
return false;
}
</script><a onclick=»return verocultar(this);»
href=»javascript:void(0);»>поменяем</a><div>
……. текст текст текст…….
</div>
Есть ещё вариант без кнопки. Работает туда и обратно, один раз
<script>function changeText(){ document.getElementById(‘boldStuff’).innerHTML = (document.getElementById(‘boldStuff’).innerHTML == ‘Нажать’) ? ‘Вот вам и второй текст’ : ‘А это снова первый’;</script>
<span id=’boldStuff’ onclick=»changeText();»>Жмём</span>
В каждом из вариантов, соответственно, меняйте текстовые поля на свои. Любой
из кодов устанавливайте в сообщении в формате HTML.
Хочется надеяться, что именно это имел в виду читатель. Может и Вам
пригодится.
✱✱✱✱✱✱
Дорогие, друзья. Скорее всего это последний пост в уходящем 2020 году. Всем
спасибо за внимание к моим шпаргалкам. Всем желаю счастливого Нового года,
незабываемых и радостных праздников. Крепкого здоровья и успехов во всех
делах. Счастья Вам и Вашим близким.
С наступающим Новым 2021 годом!!!
Здесь вы можете оформить подписку на новые шпаргалки
Improve Article
Save Article
Improve Article
Save Article
The image and text can be changed by using javascript functions and then calling the functions by clicking a button. We will done that into 3 sections., in the first section we will create the structure by using only HTML in the second section we will design minimally to make it attractive by using simple CSS and in the third section we will add the JavaScript code to perform the task
- HTML Code: In this section we create the structure plus we will add Bootstrap cdn link for the button design and the fonts.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hii! GeeksforGeeks people
</h1>
<img id="myImage"
src="img/photo1.jpg" >
</div>
<div class="col-md-3"></div>
</div>
</div>
<div class="button">
<button class="btn btn-warning"
onclick=before();>
Before
</button>
<button class="btn btn-success"
onclick=afterr();>
Afterr
</button>
</div>
</body>
</html>
- CSS Code: In this section we will use some basic CSS styling to make it look as normal as possible.
CSS
<style>
img{
height: 500px;
width: 450px;
}
h1{
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button{
margin-left: 45%;
}
</style>
- Javascript Code: In this section, we will define JavaScript functions and we have taken two images, which are present in a separate “img” folder.
Javascript
<script>
function before(){
document.getElementById('myImage')
.src="img/photo1.jpg";
document.getElementById('message')
.innerHTML="Hii! GeeksforGeeks people";
}
function afterr(){
document.getElementById('myImage')
.src="img/photo2.jpg";
document.getElementById('message')
.innerHTML="Bye! GeeksforGeeks people";
}
</script>
Complete Code: It is the combination of above codes of HTMl, CSS and JavaScript.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=
<style>
img{
height: 500px;
width: 450px;
}
h1{
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button{
margin-left: 45%;
}
</style>
<script>
function before(){
document.getElementById('myImage')
.src="img/photo1.jpg";
document.getElementById('message')
.innerHTML="Hii! GeeksforGeeks people";
}
function afterr(){
document.getElementById('myImage')
.src="img/photo2.jpg";
document.getElementById('message')
.innerHTML="Bye! GeeksforGeeks people";
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hii! GeeksforGeeks people
</h1>
<img id="myImage"
src="img/photo1.jpg" >
</div>
<div class="col-md-3"></div>
</div>
</div>
<div class="button">
<button class="btn btn-warning"
onclick=before();>
Before
</button>
<button class="btn btn-success"
onclick=afterr();>
Afterr
</button>
</div>
</body>
</html>
Output:
HTML and CSS both are foundation of webpages. HTML is used for webpage development by structuring websites, web apps and CSS used for styling websites and webapps. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn more about HTML and CSS from the links given below:
- HTML Tutorial and HTML Examples.
- CSS Tutorial and CSS Examples.
- JavaScript Tutorial and JavaScript Examples.
Improve Article
Save Article
Improve Article
Save Article
The image and text can be changed by using javascript functions and then calling the functions by clicking a button. We will done that into 3 sections., in the first section we will create the structure by using only HTML in the second section we will design minimally to make it attractive by using simple CSS and in the third section we will add the JavaScript code to perform the task
- HTML Code: In this section we create the structure plus we will add Bootstrap cdn link for the button design and the fonts.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hii! GeeksforGeeks people
</h1>
<img id="myImage"
src="img/photo1.jpg" >
</div>
<div class="col-md-3"></div>
</div>
</div>
<div class="button">
<button class="btn btn-warning"
onclick=before();>
Before
</button>
<button class="btn btn-success"
onclick=afterr();>
Afterr
</button>
</div>
</body>
</html>
- CSS Code: In this section we will use some basic CSS styling to make it look as normal as possible.
CSS
<style>
img{
height: 500px;
width: 450px;
}
h1{
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button{
margin-left: 45%;
}
</style>
- Javascript Code: In this section, we will define JavaScript functions and we have taken two images, which are present in a separate “img” folder.
Javascript
<script>
function before(){
document.getElementById('myImage')
.src="img/photo1.jpg";
document.getElementById('message')
.innerHTML="Hii! GeeksforGeeks people";
}
function afterr(){
document.getElementById('myImage')
.src="img/photo2.jpg";
document.getElementById('message')
.innerHTML="Bye! GeeksforGeeks people";
}
</script>
Complete Code: It is the combination of above codes of HTMl, CSS and JavaScript.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=
<style>
img{
height: 500px;
width: 450px;
}
h1{
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button{
margin-left: 45%;
}
</style>
<script>
function before(){
document.getElementById('myImage')
.src="img/photo1.jpg";
document.getElementById('message')
.innerHTML="Hii! GeeksforGeeks people";
}
function afterr(){
document.getElementById('myImage')
.src="img/photo2.jpg";
document.getElementById('message')
.innerHTML="Bye! GeeksforGeeks people";
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hii! GeeksforGeeks people
</h1>
<img id="myImage"
src="img/photo1.jpg" >
</div>
<div class="col-md-3"></div>
</div>
</div>
<div class="button">
<button class="btn btn-warning"
onclick=before();>
Before
</button>
<button class="btn btn-success"
onclick=afterr();>
Afterr
</button>
</div>
</body>
</html>
Output:
HTML and CSS both are foundation of webpages. HTML is used for webpage development by structuring websites, web apps and CSS used for styling websites and webapps. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn more about HTML and CSS from the links given below:
- HTML Tutorial and HTML Examples.
- CSS Tutorial and CSS Examples.
- JavaScript Tutorial and JavaScript Examples.
- JavaScript Change Button Text on Load
- JavaScript Change Button Text on Mouseover
- JavaScript Change Button Text on Click
- JavaScript Change Button Text Using jQuery

We aim to learn about JavaScript change button text via example code. It shows how the button text changes on load, click, and mouseover. It also exemplifies the use of jQuery to change the button text.
JavaScript Change Button Text on Load
If you have HTML <input> Element like input[type='button'] or input[type='submit'] then you can change button text in the following way.
HTML Code:
<input id="btn" type="button" value="Update">
<input id="btnSubmit" type="submit" value="Update">
JavaScript Code:
document.querySelector('#btn').value = 'Remove';
document.querySelector('#btnSubmit').value = 'Remove';
You can also change button text of HTML <button> Element by using any of given methods below (given methods are .innerHTML, .innerText, and .textContent).
HTML Code:
<button id="btn" type="button" value="Show Result">Show Result</button>
<button id="btnSubmit" type="submit" value="Submit Result">Submit Result</button>
JavaScript Code:
//querySelector selects the element whose id's value is btn
document.querySelector('#btn').innerHTML = 'Hide Result';
document.querySelector('#btn').innerText = 'Hide Result';
document.querySelector('#btn').textContent = 'Hide Result';
//querySelector selects the element whose id's value is btnSubmit
document.querySelector('#btnSubmit').innerHTML = 'Hide Result';
document.querySelector('#btnSubmit').innerText = 'Hide Result';
document.querySelector('#btnSubmit').textContent = 'Hide Result';
Can we use .innerHTML, .innerText, and .textContent for HTML <input> element? No. The reason is <input> is an empty element while <button> is a container tag and has .innerHTML, .innerText, and .textContent properties.
Though the goal is achieved by using .innerHTML, .innerText, and .textContent, you must have certain points in your mind.
- You may have to face cross-site security attacks due to using JavaScript
.innerHTML. - JavaScript
.innerTextreduces the performance because it needs details about the layout system. - JavaScript
.textContentdoes not arises any security concerns like.innerHTML. It also does not have to parse the HTML Content like.innerTextwhich results in the best performance.
Now, you know the differences between them. So, choose any of these methods that suit your project requirements. You can read more about them here.
JavaScript Change Button Text on Mouseover
HTML Code:
<button class="button">Hide Result</button>
CSS Code:
.button {
background-color: red;
}
.button:hover {
background-color: green;
}
JavaScript Code:
let btn = document.querySelector(".button");
btn.addEventListener("mouseover", function() {
this.textContent = "Show Result!";
})
btn.addEventListener("mouseout", function() {
this.textContent = "Hide Result";
})
The code above should show an output where the button’s text and color change when your mouse pointer hovers the button.
The querySelector() outputs the first element that matches the defined selector. The addEventListener() attaches an event handler to the given element and sets up a method for triggering a particular event.
We use mouseover and mouseout events, and the .textContent changes the button text.
JavaScript Change Button Text on Click
HTML Code:
<input onclick="changeText()" type="button" value="Hide Result" id="btn">
JavaScript Code:
function changeText(){
let element = document.getElementById("btn");
if (element.value=="Hide Result")
element.value = "Show Result";
else
element.value = "Hide Result";
}
changeText() runs when you click on the button. This method gets the first element that matches the specified selector using getElementById(). Then, it checks the element’s value and changes according to the if-else statement.
JavaScript Change Button Text Using jQuery
HTML Code:
<!DOCTYPE>
<html>
<head>
<title>Change Text</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<button id="button" onclick="changeText()">Hide Result</button>
</body>
</html>
JavaScript Code:
function changeText(){
$("#button").html('Show Result');
$("#button").css('background-color', 'green');
}
The code above changes the button’s text from Hide Result to Show Result when you click on the button, and it also changes the button’s color to green.
The .html() sets the content of the selected element while .css() changes the background-color to green. Remember, .html() is used to for HTML <button> element.
For more detail of these functions, check this link.
You might be thinking about how can we change the text using jQuery if we have HTML <input> element? The following code is for you to understand.
HTML Code:
<!DOCTYPE>
<html>
<head>
<title>Change Text</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="button" id="btnShow" value="Show" onclick="changeText()">
</body>
</html>
JavaScript Code:
function changeText(){
$("#btnShow").attr('value', 'Hide'); //versions older than 1.6
$("#btnShow").prop('value', 'Hide'); //versions newer than 1.6
$("#btnShow").css('background-color', 'yellow');
}
You can use .attr() or prop() (depending on jQuery version) to change the button text of HTML <input> element. Both, .attr() and .prop() targets the value attribute of <input> element and changes its value according to the second parameter.
In this sample code, the second parameter is Hide. The changeText() method also changes the background color to yellow using .css() function.
This post will discuss how to change the text of a button in JavaScript and jQuery.
The button element is now preferred way to create buttons over <input> element of type button. There are several ways to change the button‘s label text, which is inserted between its opening and closing tags.
1. Using jQuery
With jQuery, you can use the .text() method to replace the button‘s label text. This is demonstrated below:
JS
|
$(document).ready(function() { $(‘#submit’).click(function() { $(this).text(‘Processing…’); }) }); |
HTML
|
<!doctype html> <html lang=«en»> <body> <button id=«submit»>Submit</button> </body> </html> |
Edit in JSFiddle
Note that the .text() method will escape the provided text as necessary to render correctly in HTML.
Alternatively, you can use jQuery’s .html() method to replace an element’s content with the new content completely. It uses the browser’s innerHTML property and doesn’t escape the provided text, leading to cross-site security attacks.
JS
|
$(document).ready(function() { $(‘#submit’).click(function() { $(this).html(‘Processing…’); }) }); |
HTML
|
<!doctype html> <html lang=«en»> <body> <button id=«submit»>Submit</button> </body> </html> |
Edit in JSFiddle
2. Using JavaScript
In pure JavaScript, you can use either innerHTML, innerText or textContent to write text inside an element. Among them, textContent has better performance because its value is not parsed as HTML, and it also prevents XSS attacks.
JS
|
document.getElementById(‘submit’).onclick = function() { this.textContent = ‘Processing…’; } |
HTML
|
<!doctype html> <html lang=«en»> <body> <button id=«submit»>Submit</button> </body> </html> |
Edit in JSFiddle
That’s all about changing the text of a button in JavaScript and jQuery.
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Happy coding 


