Switching between two javascript files with checkbox

Lets say I have two javascript/jquery files. file1.js and file2.js. I want to switch between these two files with checkbox selection as I need. Something like;

<label>
    <input type="checkbox" name="file1.js" class="selector" />File1</label>
<label>
    <input type="checkbox" name="file2.js" class="selector" />File2</label>

When File1.js is selected, File2.js should be disabled, vice versa.
How would it work?

Then why not use a radio instead?

yes, you’re right. my bad. so how would it be done?

That’d be just regular HTML:

<label>
  File 1
  <input type="radio" name="file">
</label>
<label>
  File 2
  <input type="radio" name="file">
</label>

If you do need to use checkboxes (e.g. to be able to un-select a chosen option), that could be done like this (using jQuery as per your topic tag):

var checkboxes = $('.selector')

checkboxes.on('change', function (event) {
  var current = event.target

  checkboxes.each(function () {
    this.disabled = current.checked && this !== current
  })
})
1 Like

thanks, m3g4p0p, I will try that.

I’m… not… sure that @m3g4p0p 's answer actually drives to the point of the OP.

The flat answer is that the .js files would have to be coded in such a way as to be reading the input to see whether its active or not, or else implementing its methods in object-oriented design pattern and then overwriting the object repeatedly. Javascript doesn’t strictly support ‘unloading’ of functions/code.

2 Likes

Ah yes thanks, I misread the question as how to disable the checkbox, not the JS… so no, you can’t simply disable a certain script once it is loaded. The scripts in question would have to expose means to disable themselves (e.g. if one script adds event listeners to the DOM, it might expose a destroy() function that removes those event listeners and tidies everything up).

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.