JAN
JAN

Reputation: 21875

Trying to change button's contents each hit fails

Given the code :

<html>
<head>
<script src="jquery-2.1.0.min.js"></script>
Something...
</head>

<button id='flip' type='button'>Flip</button>
<script>
$('#flip').bind('click', function() {
    var x = document.getElementById("flip").name;
    if (x == 'Flip')
    {
        $(this).text('Flop');
    }

    else
    {
        $(this).text('Flip');
    }

});

</script>

</body>
</html>

I'm trying to change the button each time it is clicked , but it doesn't work .

Any idea how to fix it ?

Much appreciated

Upvotes: 1

Views: 30

Answers (2)

royhowie
royhowie

Reputation: 11171

I would do something like this:

HTML:

<button id="flipflop">flip</button>

javascript:

var flip = true;
$("#flipflop").click(function(){
    if(flip)
        $("#flipflop").text("flop");
    else
        $("#flipflop").text("flip");
    flip = !flip;
})

FIDDLE

edit: if you want to be really savvy, I would use the following line:

var flip = ($("#flipflop").text() === "flip");

Which automatically determines which way you need to flip (or is it flop?).

Upvotes: 1

Ivan Nevostruev
Ivan Nevostruev

Reputation: 28733

There is no name attribute on your <button>, so you'll always get empty value. No need for document.getElementById because button is in this. Simply call text() without parameters to get current value:

var x = $(this).text();

Update

Here is demo in JsFiddler.

Upvotes: 2

Related Questions