Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript not working when imported into html from js file?

I have some code in a .js file that is used in checkboxes. When imported into the html, though, the first two checkbox sections work (location, pop) but the last one does not. When I have the js in the html instead of importing it, all three sections (location, pop, tuition) work… I’m not sure why this is or how to fix it! Sorry for the basic question.

HTML:

    <script src="checkbox.js"></script>

JS:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var allCheckboxes = document.querySelectorAll('input[type=checkbox]');
var allPlayers = Array.from(document.querySelectorAll('.school'));
var checked = {};

getChecked('pop');
getChecked('location');
getChecked('tuition');

Array.prototype.forEach.call(allCheckboxes, function (el) {
  el.addEventListener('change', toggleCheckbox);
});

function toggleCheckbox(e) {
  getChecked(e.target.name);
  setVisibility();
}

function getChecked(name) {
  checked[name] = Array.from(document.querySelectorAll('input[name=' + name + ']:checked')).map(function (el) {
    return el.value;
  });
}

function setVisibility() {
  allPlayers.map(function (el) {
    var pop = checked.pop.length ? _.intersection(Array.from(el.classList), checked.pop).length : true;
    var location = checked.location.length ? _.intersection(Array.from(el.classList), checked.location).length : true;
    var tuition = checked.tuition.length ? _.intersection(Array.from(el.classList), checked.tuition).length : true;
    if (pop && location && tuition) {
      el.style.display = 'block';
    } else {
      el.style.display = 'none';
    }
  });
}

The tuition does not change when checkboxes are selected.

>Solution :

Make sure the script is loaded at the bottom of your HTML document, or better, use the defer attribute so the script wait for the entire HTML to be ready before running.

Having the script being executed too early can make it try to manipulate HTML tags that are not yet ready.

For more information you can check this answer, which explains in details what happens when loading a script within an HTML page.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading