Skip to content
Advertisement

Changing display text on a button and back again using Javascript [closed]

I’m been trying multiple attempts to change the text on a button so that when the form opens it shows the text “Add Challenging Questions” and if you click it, it unhides a div, but then I want the text of the button to change to “Remove Challenging Questions” and if it’s clicked it hides that div again. The code I have works with regards to showing and hiding the div, but nothing I’ve tried affects the text of the button.

I’ve also tried buttonName.value and buttonName.innerText. The developer tools show a “uncaught type error” and says it cannot set the property. Any idea what is wrong?

document.getElementById("cqButton").addEventListener("click", function() {
  myFunction("cqSubsDiv");
});


function myFunction(someDiv) {
  var divDisplay = document.getElementById(someDiv);
  var buttonName = document.getElementById(cqButton);
  if (divDisplay.style.display === "none") {
    divDisplay.style.display = "block";
    buttonName.innerHTML = 'Remove Challenging Questions';
  } else {
    divDisplay.style.display = "none";
    buttonName.innerHTML = 'Add Challenging Questions';
  }
}
<button id="cqButton" name="cqButton" class="btn btn-primary">Add Challenging Questions</button>

Advertisement

Answer

You have a typo (missing quotes in document.getElementById(‘cqButton’))

But you also need to delegate

I wrapped the buttons in a div. When something in the div is clicked, I test to see if it has class cqButton. If it does, I get the ID of the div to show from the data attribute and toggle the hide class on that div. then I look to see if the div I just toggled has the hide class or not to determine the text in the button

document.getElementById("container").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("cqButton")) {
    const divDisplay = document.getElementById(tgt.dataset.div);
    divDisplay.classList.toggle("hide")
    tgt.innerHTML = divDisplay.classList.contains('hide') ? 'Add Challenging Question': 'Remove Challenging Question';
  }
})
.hide { display: none; }
<div id="container">
  <button data-div="cqSubsDiv1" class="cqButton btn btn-primary">Add Challenging Question</button>
  <button data-div="cqSubsDiv2" class="cqButton btn btn-primary">Add Challenging Question</button>
</div>

<div id="cqSubsDiv1" class="hide">challenging question 1</div>
<div id="cqSubsDiv2" class="hide">challenging question 2</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement