2

So I am trying to get the text in the button to toggle between strings stored in the data attributes:

<button class="toggleButton6 book1" data-starttext="Starting Text" data secondtext="Toggled Text">Starting Text</button>

So far I can get the text to change only for the first click event. I need to add something to get the text to toggle back and forth with unlimited click events:

$(document).ready(function(){
  $('.book1').on('click', function(){
    var textVariable = $(this).data("secondtext");
    $(this).text(textVariable);
  });
});

http://codepen.io/nigelNSF/pen/Dfpak

1
  • 2
    Possible typo in your code: data secondtext. Should be data-secondtext Commented Jun 7, 2013 at 16:44

4 Answers 4

8

You don't need 2 data as you have the firsttext as button.text(), so change your html like below to have just 1 data.. lets say toggletext

<button class="toggleButton6 book1" data-toggletext="Toggled Text" >Starting Text</button>

And then toggle the value of toggletext and button.text() in the script like below,

$(document).ready(function(){
  $('.book1').on('click', function(){
        var textVariable = $(this).data("toggletext");          
        $(this).data('toggletext', $(this).text()).text(textVariable);

  });
});

DEMO: http://codepen.io/seraphzz/full/IJLBi

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

Comments

0
$(document).ready(function(){
  $('.book1').on('click', function(){
    if ($(this).text() == $(this).attr('data-starttext'))
        $(this).text($(this).attr('data-secondtext'));
    else 
        $(this).text($(this).attr('data-starttext'));
  });
});

Comments

0

try this:

$(document).ready(function(){
  $('.book1').on('click', function(){
      var textVariable = $(this).data("secondtext");
      var temp = $(this).text();
      $(this).text(textVariable).data("secondtext", temp);
  });
});

Comments

0

As everybody else says: you must check the state of the text by comparing it to starttext or secondtext and explicitly setting the value of your text field accordingly.

$(document).ready(function(){
  $('.book1').on('click', function(){
    var second = $(this).data("secondtext");
    var start = $(this).data("starttext");
    if (second === $(this).text()) {
      $(this).text(start);
    } else {
      $(this).text(second);
    }
  });
});

Here is a working example.

Comments

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.