简体   繁体   中英

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.

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:

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

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.

Try this.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM