简体   繁体   中英

javascript disable checkbox when another checkbox is checked with same name

I'm trying to make a little quiz in my project. The idea is when one checkbox is clicked, the other option should be disabled. I'm have tried with radio control, but it doesn't work, because I have more than one question with same checkbox name.

Here is my current code

<form name=f1 method=post action="">
    <label>soal 1</label><br>
<input type=checkbox name=domi[] onclick="domi1(this.checked)" >A<br>
<input type=checkbox name=influ[] onclick="influ1(this.checked)">B<br><br>

    <label>soal 2</label><br>
<input type=checkbox name=domi[] onclick="influ2(this.checked)" >A<br>
<input type=checkbox name=influ[] onclick="stedi1(this.checked)">B<br><br>

<button type="submit">simpan</button>
</form>

Javascript code disabled the controls

 <SCRIPT LANGUAGE="JavaScript">
    function domi1(status)
    {
    status=!status; 
    document.f1.influ1.disabled = status;
    }

    function influ1(status)
    {
    status=!status; 
    document.f1.domi1.disabled = status;
    }
    </script>

Seems like you could use radio inputs (same name is not a problem), but assuming you have some other reason to use checkboxes why not add ids or classes to your input elements to simplify things a bit? Here is a basic example using ids and replacing your inline function calls with addEventListener :

 const inputs = document.querySelectorAll('input[type="checkbox"]'); for (let input of inputs) { input.addEventListener('click', (event) => { if (event.target.id === 'domi1') { document.querySelector('#influ1').disabled = true; } else if (event.target.id === 'influ1') { document.querySelector('#domi1').disabled = true; } }); } 
 <span>soal 1</span> <br> <input type="checkbox" name="domi[]" id="domi1"> <label for="domi1">A</label> <br> <input type="checkbox" name="influ[]" id="influ1"> <label for="influ1">B</label> 

Also a version using radio inputs instead:

 const inputs = document.querySelectorAll('input[type="radio"]'); for (let input of inputs) { input.addEventListener('click', (event) => { if (event.target.id === 'domi1') { document.querySelector('#influ1').disabled = true; } else if (event.target.id === 'influ1') { document.querySelector('#domi1').disabled = true; } }); } 
 <span>soal 1</span> <br> <input type="radio" name="domi[]" id="domi1"> <label for="domi1">A</label> <br> <input type="radio" name="influ[]" id="influ1"> <label for="influ1">B</label> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM