1

I have an issue with jquery mobile and a button text switch.

The button text should change everytime sie button is clicked. It is working one time only. I click the button, the text and backgound changes, the second time I click it nothing happens. Here ist my code:

Button declaration:

<div data-role="header">
    <div data-role="navbar">
      <ul>
        <li><a href="#" id="lock" class="lockaction" >Lock</a></li>
      </ul>
    </div>
  </div>

And here the function I have:

$(".lockaction").click(function(e) { 

            if (e.target.id == "lock" ) {

                document.getElementById("lock").text = "Unlock";
                $(this).css("background-color", "red");

                }

            else {

                document.getElementById("lock").text = "Lock";

                }

        postupdate();

    });

Maybe someone can help me with it.

1
  • It fails bacause your ID is always "lock". Check for text in element instead. Commented Jun 4, 2015 at 8:31

2 Answers 2

1

It fails bacause your ID is always "lock". Check for text in element instead.

Try something like this:

$(".lockaction").click(function(e) { 

    e.preventDefault();

    if ($(this).text() === "Lock" ) {
        $(this).text("Unlock");
        $(this).css("background-color", "red");
    } else {
        $(this).text("Lock");
        $(this).css("background-color", "white");
    }

    postupdate();

});

Fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

Np, please select one of the answers if they helped you.
0

You need to check what value does the text contains. You were checking for id, it will always return true as the id wont change, so your if is always true.

$(".lockaction").click(function (e) {
    e.preventDefault();//prevent default action
    if ($(this).text() == "Lock") {
        $(this).text("Unlock");
        $(this).css("background-color", "red");

    } else {
        $(this).text("Lock");
        $(this).css("background-color", "white");
    }
    postupdate();

});

1 Comment

Thanks, I tried it and it wasn´t working. With "e.preventDefault();" like Drops did it, it´s working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.