Search code examples
jquerytwitter-bootstrapbuttontoggle

Changing Bootstrap button text on toggle


I currently have a collapse button built with Bootstrap and I'm trying to transform the text from 'Read more' to 'Read less'. I've been trying jQuery, but I just can't get it to work.

<a data-toggle='collapse' href='#collapseExample' id='#collapseExample' class='text-center btn btn-default'>Read More</a>
    <div class='collapse' id='collapseExample'>
        <p class='readmore'>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
    </div>


$(document).ready(function(){
 $('#collapseExample').on('click', function () {
  var text=$('#collapseExample').val();
  if(text==='Read more'){
    $(this).text('Read less');
  } else{
    $(this).text('Read more');
 }
});
})     

Solution

    1. Don't use same id twice in a html page that's invalid.

    2. Don't start a id with # can cause a lot of problem while using in jquery.

    3. The strings must match exactly so Read more won't work, you need to use Read More.

    4. Don't use val() instead use text() or html()

    Working snppet

    $(document).ready(function(){
     $('#collapseExample1').on('click', function () {
      var text=$('#collapseExample1').text();
      if(text === "Read More"){
        $(this).html('Read less');
      } else{
        $(this).text('Read More');
     }
    });
    });
    <a data-toggle='collapse' href='#collapseExample' id='collapseExample1' class='text-center btn btn-default'>Read More</a>
        <div class='collapse' id='collapseExample2'>
            <p class='readmore'>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
        </div>
    
    
      <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
              <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
              <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>