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>
1
  • Possible duplicate of link Commented Feb 6, 2019 at 22:54

2 Answers 2

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";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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>

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.