Changing button text onclick

2020-01-24 20:30发布

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?

16条回答
男人必须洒脱
2楼-- · 2020-01-24 21:05

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";
          }
查看更多
Bombasti
3楼-- · 2020-01-24 21:07

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>

查看更多
闹够了就滚
4楼-- · 2020-01-24 21:11

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>
查看更多
爷、活的狠高调
5楼-- · 2020-01-24 21:12
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>
查看更多
登录 后发表回答