Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change button text in jQuery

I have a table which I want to hide or show on the click of a button. Also, when the button is clicked, its text should be changed appropriately. I have the following code, but the button's text is not being changed:

<script>
        $(document).ready(function () {
            $("#myButton").click(function () {
                $(".myTable").toggle(1000, "linear", function changeButtonText() {
                    $("#myButton").text = ($("#myButton").text === "Hide table" ? "Show table" : "Hide table");
                });
            });
        });
</script>

... 

<input type="button" id="myButton" value="Hide table" />
<table class="myTable">
    ...
</table>
like image 853
Eutherpy Avatar asked Oct 26 '25 08:10

Eutherpy


1 Answers

You didn't use the function in the right way:


  • If the element is button:

Error:

$("#myButton").text = ("new text");

Work:

$("#myButton").text("new text");

Working example:

$("#myButton").text("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="myButton">Old text</button>

  • If the element is input type="button":

Error:

$("#myButton").text = ("new text");

Work:

$("#myButton").val("new text");

Working example:

$("#myButton").val("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" id="myButton" value="Hide table" />
like image 104
Marco Salerno Avatar answered Oct 28 '25 21:10

Marco Salerno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!