How to change the text of a button in jQuery?

2019-01-01 14:24发布

How do you change the text value of a button in jQuery? Currently, my button has 'Add' as its text value, and upon being clicked I want it to change to 'Save'. I have tried this method below, but so far without success:

$("#btnAddProfile").attr('value', 'Save');

21条回答
永恒的永恒
2楼-- · 2019-01-01 14:37
$("#btnAddProfile").click(function(){
    $("#btnAddProfile").attr('value', 'Save');
 });
查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 14:38

For buttons created with .Button() in jQuery........

Whilst the other answers will change the text they will mess up the styling of the button, it turns out that when a jQuery button is rendered the text of the button is nested within a span e.g.

<button id="thebutton">
  <span class="ui-button-text">My Text</span>
</button>

If you remove the span and replace it with text (as in the other examples) - you'll loose the span and associated formatting.

So you actually need to change the text within the SPAN tag and NOT the BUTTON!

$("#thebutton span").text("My NEW Text");

or (if like me it's being done on a click event)

$("span", this).text("My NEW Text");
查看更多
长期被迫恋爱
4楼-- · 2019-01-01 14:38

Have you gave your button a class instead of an id? try the following code

$(".btnSave").attr('value', 'Save');
查看更多
零度萤火
5楼-- · 2019-01-01 14:38
$("#btnviewdetails").click(function(){
    if($(this).val()!="hide details"){
        $("#detailedoutput").show();
        $(this).val('hide details');
    }else{
        $("#detailedoutput").hide();
        $(this).val('view more details');
    }

});
查看更多
裙下三千臣
6楼-- · 2019-01-01 14:40

To change the text in of a button simply execute the following line of jQuery for

<input type='button' value='XYZ' id='btnAddProfile'>

use

$("#btnAddProfile").val('Save');

while for

<button id='btnAddProfile'>XYZ</button>

use this

$("#btnAddProfile").html('Save');

查看更多
登录 后发表回答