-2

I have a toggle on button in my Application.

If the button ist toggled on, I want that the value is set to 1, and if not the value should be null. (0=deactivated, 1=activated)

Thats my current javascript code:

var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener( 'change', function() {
    if(this.checked) {
        document.getElementById("activate").value = '1';
    } else {
        document.getElementById("deactivate").value = '0';
    }
});

And thats my toggle button:

<div class="toggle">
    <label>
         <input id="CheckAcitavtion" name="checkbox" type="checkbox"> 
         <span class="slider"></span>
    </label>
</div>  

But at the moment when I toggle the button the following error shows up:

Uncaught TypeError: Cannot set property 'value' of null at HTMLInputElement.

R3tep
  • 11,061
  • 9
  • 38
  • 69
Trayer
  • 93
  • 2
  • 10
  • 4
    There is no html element with the "activate" or "deactivate" id? – Wouter Vandevelde Oct 06 '17 at 09:41
  • try doing with **id** instead of **querySelector**. Change it to `element = document.getElementById(id);` and set the `id` to the button one. – ZombieChowder Oct 06 '17 at 09:42
  • @ZombieChowder — The problem is with the code which uses `document.getElementById`. The only use of `document.querySelector` in the question is absolutely fine. – Quentin Oct 06 '17 at 09:43
  • There's no element with the id that is being searched for. Voting to close this question as off-topic. It's basically a typo question. It's certainly not a useful question. – Quentin Oct 06 '17 at 09:43
  • I'm sorry for that typo I didn't noticed it before I was posting this, it was from an old version. Thanks – Trayer Oct 06 '17 at 09:50

1 Answers1

1

The id's you pointed to didn't exist so i gave the span element this id. You should also use innerHTML instead of value for an element that isn't <input>.

var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener( 'change', function() {
    if(this.checked) {
        document.getElementById("checkValue").innerHTML = '1';
    } else {
        document.getElementById("checkValue").innerHTML = '0';
    }
});
<div class="toggle">
  <label>
  <input id="CheckAcitavtion" name="checkbox" type="checkbox">
    <span id="checkValue">0</span>
  </label>
</div>