3

I have a working script that toggles my div, and it works great but I can't figure out how to also change the button text when clicked. I need the button text to be "Hide Spreads" when the spread div is shown, and "Show Spreads" when the spread div is not shown.

Script:

$(document).ready(function(){
  $(".spread").show();
  $(".show_hide").show();
  $('.show_hide').click(function(){
    $(".spread").toggle();
  });
});

Button:

<input type="button" class="show_hide" value="Hide Spreads" />

2 Answers 2

6

You can use $(this).val() to get value of the button and check it against the other possible value.

$('.show_hide').click(function(){
    $(".spread").toggle();
    $(this).val( $(this).val() == 'Hide Spreads' ? 'Show Spreads' : 'Hide Spreads' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="button" class="show_hide" value="Hide Spreads">
<div class="spread">Test</div>

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

1 Comment

Awesome, thank you. I was so close earlier, I was missing the .val(). Will accept as answer when allowed.
3

you can use $(this).text() for get button text and change it by if else.

<button id="show_hide">Show</button>
<div id="display"></div>
<script>
$("#show_hide").click(function(){
    $("#display").toggle();
    if($(this).text() == "Show"){
       $(this).text("Hide");
    }else{
       $(this).text("Show");
    }
});
</script>

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.