0

Still learning the ropes of JS and attempting to create a function that will toggle a button on and off, this works just fine. using the following. (Please ignore the handlebars.js)

What I'm wondring is how do I create a single function to handle 6 seperate toggles.

Cheers in advance,

a newbie.

       
        function toggle(button)
  {
  if(document.getElementById("1").value=="OFF"){
   document.getElementById("1").value="ON";}
 
  else if(document.getElementById("1").value=="ON"){
   document.getElementById("1").value="OFF";}
                                                     }
     
   
    
    <input type="button" id="1" {{#if profile.userSettings.notificationSettings.enabled}} value="ON" {{else}} value="OFF" {{/if}} onclick="toggle(this);  ">
Lewis Clarke
  • 69
  • 2
  • 12
  • @Zenoo Wow, thanks so much. That actually explained alot. With regards to the numericals in an ID, whats the reasoning on that? Just bad practice? – Lewis Clarke Apr 12 '18 at 09:57
  • You should look at https://stackoverflow.com/questions/5672903/can-i-have-a-div-with-id-as-number for more info about ids. If you want to answer to someone in the future, you should comment under his answer, not under your question. If I didn't go back to see this question I would have never known you answered. Also, don't forget to validate the answer if it solved your issue. – Zenoo Apr 13 '18 at 07:05

1 Answers1

0

First of all, don't start an ID with a numeric.

For you main issue, you can simply use the parameter button of your function and check its value.

function toggle(button){
  button.value = button.value == 'OFF' ? 'ON' : 'OFF';
}
<input type="button" value="ON" onclick="toggle(this);">
<input type="button" value="OFF" onclick="toggle(this);">
<input type="button" value="ON" onclick="toggle(this);">

PS :

button.value = button.value == 'OFF' ? 'ON' : 'OFF'

Is the ternary operator equivalent of

if(button.value == 'OFF'){
    button.value = 'ON';
}else{
    button.value = 'OFF';
}
Zenoo
  • 12,670
  • 4
  • 45
  • 69