0

I would like to toggle the text when the div is clicked but I can't make it work. I can make it change once using this

$(document).ready(function() { 
    $(".select_button").on("click", function() {
        $(this).find('.selected').text('Image Selected');
    });
});

But I'm trying to get it to toggle

This is the HTML

<div class="select_button">
       <label>
            <input type="checkbox" name="include_standard" class="include_standard"
               value="<? echo $row['newest_image']; ?>">
             <span class="selected">Use Image</span>
       </label>
</div>

And this is the JQuery

$(document).ready(function() { 
   $(".select_button").on("click", function() {
      $(this).find('.selected').text(text() == 'Use Image' ? 'Selected': 'Use Image');
    });
});

It doesn't throw any errors or doing anything.

5 Answers 5

2

I'd suggest:

$(".select_button").on("click", function () {
    $(this).find('.selected').text(function (i, oldText) {
        return $.trim(oldText) == 'Use Image' ? 'Selected' : 'Use Image';
    });
});

JS Fiddle demo.

References:

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

Comments

0
<script>
$(document).ready(function(){
  $(".select_button").mousedown(function(){
     $(this).text("Your New Text")
 });
 $(".select_button").mouseup(function(){
     $(this).text("Your Old Text")
 });
});
</script>

2 Comments

As soon as I move the mouse away it changes back, perhaps I should have made the questions clearer, I would like the new value to stay until I click on the button again.
@tatty27, tr yusing my new answer
0
<script>
$(document).ready(function(){
  $(".select_button").click(function(){
     $(this).addClass("NewClass");
     $(this).text("Your New Text");
 });
 $(".NewClass").click(function(){
     $(this).removeClass("NewClass");
     $(this).text("Your Old Text");
 });
});
</script>

Comments

0

Do you have another text() method in scope you can call?

This could mean that it is returning undefined every time causing 'Use Image' to always be returned from your ternary statement.

I would suggest storing your find result for $(this).find('.selected') into a variable and then calling .text() on that variable in order to get the text from the element with the selected element.

Comments

0

Try this.

$(document).ready(function() { 
   $(".select_button").on("click", function() {

   var spanvar = $(this).find('.selected');
   $(spanvar).text(spanvar.text() == 'Use Image' ? 'Selected': 'Use Image');
   });
});

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.