Wyatt McLaren
Wyatt McLaren

Reputation: 11

Controlling javascript with checkbox

I'm building a chrome extension where i want to control javascript with this checkbox :

    <div class="modal-icons">
        <div class="flex-container">
            <div class="flex">
                <label class="switch">
                  <input id="check" type="checkbox" checked>
                  <span class="slider round"></span>
                </label>
            </div>
        </div>
    </div>

How can i get the state in the .js file?

I have tried :

document.addEventListener('DOMContentLoaded', function() {
const checked = document.getElementById('check').checked;
  # ACTION 
  });

and

var checked = document.getElementById('check').checked;
console.log('checked');

And also similar approaches but I'm not sure how to get the state.

I get the error message : Uncaught TypeError: Cannot read property 'checked' of null

Can I write this for instance?

if (checked == true) {
   console.log('checked');
}

Or will it give a value of 'checked'?

Could someone help me to explain this, please?

Upvotes: 1

Views: 171

Answers (2)

Wyatt McLaren
Wyatt McLaren

Reputation: 11

Finally this solved my problem :

document.getElementById('check').addEventListener('change', func => {
if (event.target.checked) {
    chrome.tabs.executeScript({
    file: 'safe.js'
    }); 
    }
});

I only managed to run a script from a different file though.

Also the script file executing this code had to be named 'popup.js' and did not work with other names - even if declared in the manifest file corretly.

I think it has to do with some special requisites of Chrome extensions.

Upvotes: 0

Luke-zhang-04
Luke-zhang-04

Reputation: 793

The problem with

var checked = document.getElementById('check').checked;
console.log('checked');

is that the variable checked stays one value and is never updated, i.e if the checkbox is checked by default, checked is always true even if it is changed. In addition, there is nothing which listens for updates to the checkbox.

I would bind an event listener to the element

document.getElementById('check').addEventListener("change", event => {
    if(event.target.checked) {
        // Checkbox is checked
    } else {
        // Checkbox is not checked
    }
})

Upvotes: 1

Related Questions