tatty27
tatty27

Reputation: 1554

Toggle text in span using JQuery

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.

Upvotes: 0

Views: 406

Answers (5)

Arjit
Arjit

Reputation: 3456

Try this.

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

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

Upvotes: 0

evasilevsky
evasilevsky

Reputation: 175

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.

Upvotes: 0

Mark
Mark

Reputation: 4873

<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>

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

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:

Upvotes: 2

Mark
Mark

Reputation: 4873

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

Upvotes: 0

Related Questions