Sheehan Alam
Sheehan Alam

Reputation: 60919

How can I change the text of a <span> element?

I have a toggle button that I'm adding to an iFrame:

<script>
    $('#list div').each(function(){
        $(this).append('<span class="togglebutton">Maximize</span>');   
    });

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
    });
</script>

How can I change the toggle between the text Maximize/Minimize when the toggleClass is maximized?

Upvotes: 0

Views: 159

Answers (4)

David Hammond
David Hammond

Reputation: 3306

$("span.togglebutton").toggle(function() {
    $(this).closest("li").children("div").addClass("maximized")
    $(this).text("Maximized Text");
},function(){
    $(this).closest("li").children("div").removeClass("maximized")
    $(this).text("Minimized Text");
});

Upvotes: 0

Korvin Szanto
Korvin Szanto

Reputation: 4511

$(this).text('New Text');

OR

$(this).val('New Text');

Determine state.

if ($this.text() == 'Maximized') {
    $(this).text('Minimized');
} else {
    $(this).text('Maximized');
}

Upvotes: 0

jondavidjohn
jondavidjohn

Reputation: 62412

$("span.togglebutton").click(function() {
    var $this = $(this);  // cache jquerized 'this'
    $this.closest("li").children("div").toggleClass("maximized");

    var currentText = $this.text();

    // if the text is currently "Maximize"
    if (currentText === "Maximize") {
        // change it to new value
        $this.text("New Text");
    }
    else {
        // change it back to "Maximize"
        $this.text("Maximize");
    }
});

Upvotes: 1

Starx
Starx

Reputation: 79069

Well, if you are looking for some function like toogleClass() to do that job for you, you are out of luck. AFAIK, you have to do it manually.

Do something like this

function toggleText() {
    var curText = $("span.togglebutton").text();
    var newText;
    if(curText=="Maximize") { newText = "Minimize"; }
    else { newText = "Maximize"; }
    $("span.togglebutton").text(newText);
}

Now you can call it happily where you want to toggle it. Like

    $("span.togglebutton").click(function() {
        $(this).closest("li").children("div").toggleClass("maximized");
        toggleText();
    });

Upvotes: 1

Related Questions