83

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
  • 771
  • 9
  • 23
Anthony Do
  • 1,409
  • 4
  • 18
  • 19

19 Answers19

80

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";
}
Parth Thakkar
  • 5,427
  • 3
  • 25
  • 34
  • 6
    Not with 'onClick', Parth. You have to pass a reference to the object: onClick="change(this)" and then in the JS: function change(button) { print button.value; } – Sp4cecat May 20 '12 at 06:13
  • oh yes...correct. I thought it would work, but when I saw your comment, i fiddled it out and it failed...i'll just make an edit – Parth Thakkar May 20 '12 at 06:17
  • @ParthThakkar on Chrome `this` does get set to the button. – Alnitak May 20 '12 at 06:18
  • horrors! I just tried on chrome, it didn't. It referred to DOMWindow – Parth Thakkar May 20 '12 at 06:20
  • Why not get the element name from the target properties of the event object that will be passed by onClick (or any other event that calls change() )? – Lee Goddard Oct 24 '13 at 07:52
  • 10
    After having some issues with this myself (and realizing I just had a syntax error), this is what I've found to work: `this.innerHTML =`. Using `this.value` didn't work for me in Firefox v28. This is for an actual button element though, rather than an input button. – Chris Middleton Apr 26 '14 at 05:09
  • Thats not working. – Coderz Way Sep 24 '22 at 13:28
42

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>

Baked Inhalf
  • 3,375
  • 1
  • 31
  • 45
  • 3
    This definetely helped me. Works great. In my opinion the simplest most straight forward answer out of all of them. `innerHTML` changes the visual text of the button. `value=""` is not visible and just holds hidden data. Thanks dude. – Micha Apr 25 '18 at 03:30
15

It seems like there is just a simple typo error:

  1. Remove the semicolon after change(), there should not be any in the function declaration.
  2. 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" />
11

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>
user1865775
  • 183
  • 1
  • 9
6

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

Bayu Zangetsu
  • 127
  • 1
  • 9
5

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>
Krisi Suci
  • 129
  • 1
  • 4
2

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>
PålOliver
  • 2,502
  • 1
  • 23
  • 27
2

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";
    }
1

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>
Sp4cecat
  • 991
  • 1
  • 8
  • 18
1

Try this,

<input type="button" id="myButton1" value="Open Curtain" onClick="javascript:change(this);"></input>
<script>
function change(ref) {
    ref.value="Close Curtain";
}
</script>
premnathcs
  • 545
  • 3
  • 11
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 :D

SixPackScript
  • 111
  • 1
  • 10
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'; }" />
Brian Bruman
  • 883
  • 12
  • 28
1
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;
Pablo Salcedo T.
  • 874
  • 1
  • 16
  • 27
0
This is simple way to change Submit to loading state   

 <button id="custSub" type="submit" class="button left tiny" data-text-swap="Processing.. &nbsp;">Submit &nbsp;<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>
0
<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>
0

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";
          }
Community
  • 1
  • 1
alphapilgrim
  • 3,761
  • 8
  • 29
  • 58
0
<!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
  • 965
  • 2
  • 18
  • 29
kaustubhd9
  • 109
  • 1
  • 6
0

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';
}
Derek Pollard
  • 6,953
  • 6
  • 39
  • 59
molecule
  • 31
  • 4
0
function change() {
 myButton1.value=="Open Curtain" ? myButton1.value="Close Curtain" : myButton1.value="Open Curtain";
}
Richard Z
  • 161
  • 2
  • 3
  • How is this really any different from [this Answer](https://stackoverflow.com/a/32364054/12695027) by [alphapilgrim](https://stackoverflow.com/users/4812515/alphapilgrim)? – Scratte Feb 08 '21 at 06:26