Change text of a button on click!

I have a collapsible button that has [+] as a prefix. when I click it I want the prefix to change to [-] and when click it again I want to change back to [+]. I decided to go with the approach for working with teh string. no booleans, no arrays. Here is my not-working code:

<button id="operators_c" class="collapsible" onclick="col(this.id)">[+]Operators</button>
<script>

function Col(i) {	
var o = Document.getElementById(i);
var sub1 = o.textContent.substring(0,4);
if sub1 == "[+]" {
o.textContent = "[-]" & o.textContent;
}
if sub1 == "[-]" {
o.textContent = "[+]" & o.textContent;
}
</script>

One obvious thing, possibly not the full answer, but you are using col and Col. You need to be consistent as to whether you want to use upper or lower case.

Using CSS results in a much easier time.

.collapsible:before {
  content: "[+]";
}
.collapsible.open:before {
  content: "[-]";
}
<button id="operators_c" class="collapsible">Operators</button>
<button id="operators_c" class="collapsible open">Operators</button>

Then, you only need to use JavaScript to add/remove the open classname on the element.

2 Likes

Hi @stan0033, there are a couple of syntax and reference errors in your code which you can see if you open the console of the browser dev tools:

  • As @Gandalf already noted, your spelling the function names differently; per convention, function names should be lower camel case except for constructor functions, which are upper camel case
  • Same thing: it’s document, not Document
  • The if conditions must be in parentheses
  • There’s a closing curly brace missing at the end

Apart from that there are also a few logical bugs:

  • You’re selecting a substring with the length of 4 (i.e. "[+]O"), so neither check will pass
  • Strings get concatenated with the + operator, the & is a bitwise AND
  • You’re then appending the complete original string, which will result in all the "[+]" and "[-]" adding up

So here’s a fixed version:

function col (id) {
  var element = document.getElementById(id);
  var prefix = element.textContent.slice(0, 3);
  var text = element.textContent.slice(3);

  if (prefix == "[+]") {
    element.textContent = "[-]" + text;
  } else if (prefix == "[-]") {
    element.textContent = "[+]" + text;
  }
}

BTW passing the ID is actually an unnecessary detour – you can pass in the element directly like so:

<button onclick="col(this)">...</button>
function col (element) {
  var prefix = element.textContent.slice(0, 3);
  // ...
}

Or better yet, avoid inline JS altogether:

<button id="operators_c">...</button>
var operatorsBtn = document.getElementById('operators_c')

operatorsBtn.addEventListener('click', function col () {
  var prefix = this.textContent.slice(0, 3);
  // ...
})
1 Like

thank you very much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.