1

I have a simple question about changing the text of a button after the user clicks it.

I would like the button click to cause the text to toggle between two values: "More" and "Less". Note that before the first click, it must have the value "More" and after the click the value "Less":

<button class="btn btn-primary" type="button"  data-toggle="collapse" data-target="#collapseExample"  aria-expanded="false" aria-controls="collapseExample">
  More
</button>

<div class="collapse" id="collapseExample">
  <p>Test</p>
</div>
Azametzin
  • 5,223
  • 12
  • 28
  • 46
Valentin
  • 405
  • 2
  • 6
  • 17
  • Possible duplicate of [link](https://stackoverflow.com/questions/25341429/jquery-read-more-read-less-how-to-replace-text) – M_M Feb 06 '19 at 22:54

2 Answers2

2

Basically, you could add an onclick event to the button referencing to a function:

<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample" onclick="changeText()">
  More
</button>

Then, you prepare the function to change the text:

function changeText () {
  if (this.innerText == "More") { // check if text inside is "More"
    this.innerText == "Less";    // If so, change to "Less"
  } else {
    this.innerText == "More";
  }
}
Azametzin
  • 5,223
  • 12
  • 28
  • 46
1

This can be achieved using vanilla javascript via the following:

/*
Fetch the buttom element
*/
const button = document.body.querySelector('[data-target="#collapseExample"]');

/*
Add click event listener where we will provide logic that updates the button text
*/
button.addEventListener('click', function() {
  
  /*
  Update the text of the button to toggle beween "More" and "Less" when clicked
  */
  if(button.innerText.toLowerCase() === 'less') {
    button.innerText = 'More';
  }
  else {
    button.innerText = 'Less';
  }
});
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
More
</button>

<div class="collapse" id="collapseExample">
   <p>Test</p>
</div>
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65