0

How to change text of button onclick?

Hello everyone, I want to change the text of a button when he is clicked. When he has prefix [+] change it to [-] else [+]. So I did this not-working attempt: <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>

29th Jul 2018, 11:54 AM
Stanislav Vladev
Stanislav Vladev - avatar
5 Respostas
+ 5
1. JavaScript is CaSe SeNsItIve language. So col and Col is a different functions (if you see javascript errors, you will get something about "undefined function col"). And also "document", not "Document" 2. What do you mean by "&" operator? If you want to concatenate strings, than use "+" operator. "[-]" + o.textContent; 3. If you want to CHANGE [-] to [+] and [+] to [-], then you must write: "[-]" + o.textContent.substring(3). This will concatenate the "[-]" to button text without a first "[+]" 4. Why you do substring(0, 4)? Length of "[-]" and "[+]" is 3 letters. Complete working code: https://code.sololearn.com/W5YqSjXTUs4n/#js
29th Jul 2018, 12:11 PM
Mishin870
Mishin870 - avatar
+ 5
Oh Am sorry Stanislav Vladev Didn't get the question See TurtleShell Code Thanks Mishin870
29th Jul 2018, 12:22 PM
Femi
Femi - avatar
0
- Col() function in the script is uppercase in the button onclick attribute it’s lowercase change one of those - Document object is uppercase, it’s lowercase so document.getElementById() - substring(0, 4) will get “[+]O” change it to (0, 3) - No need to use the & bitwise operator simply doing “[-]Operators” and “[+]Operators” will be fine Optional - Instead of passing the id just pass the object (this) it saves you fom doing document.getElementById() My version: https://code.sololearn.com/W5DxXoHMTcSs/?ref=app
29th Jul 2018, 12:15 PM
TurtleShell
TurtleShell - avatar
0
Ishola, he needs both "[+]/[-]" and the text on the button, but you just replace this text.
29th Jul 2018, 12:18 PM
Mishin870
Mishin870 - avatar