When I click on myButton1
button, I want the value to change to Close Curtain
from Open Curtain
.
HTML:
<
It seems like there is just a simple typo error:
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" />
<!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>
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>
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'; }" />
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";
}
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