Daniel Mano
Daniel Mano

Reputation: 13

Check/Uncheck radio buttons JavaScript

Can someone help me with this one? When I set a() to #j1 and b() to #j2, everything works fine (click-check one radio button, the other one gets unchecked), but when I set both to c(), it only works when I click button 2 first and then button 1, and then it gets stuck. I have also tried with a loop, but I guess there is an inherent mistake in its logic.

Thanks in advance. Daniel

<body>

    <input type="radio" id="j1" onclick="c()"><label for="j1">1</label>
    <input type="radio" id="j2" onclick="c()"><label for="j2">2</label>

    <script>
        const j1 = document.querySelector("#j1");
        const j2 = document.querySelector("#j2");

        function a(){
            j1.checked = true;
             j2.checked = false;
         }

        function b(){
            j1.checked = false;
            j2.checked = true;
        }

        function c(){
                if(j1.checked===true){
                    j2.checked=false;
                }
                else if(j2.checked===true){
                    j1.checked=false;
                }
            }
    </script>
</body>

Upvotes: 1

Views: 660

Answers (2)

Antoine Guerra
Antoine Guerra

Reputation: 421

I'm not sure to understand which you ask but i think you need something like this :

const j1 = document.querySelector("#j1");
const j2 = document.querySelector("#j2");

function a() {
    j2.checked = false;
}

function b() {
    j1.checked = false;
}
<body>
    <input type="radio" id="j1" onclick="a()"><label for="j1">1</label>
    <input type="radio" id="j2" onclick="b()"><label for="j2">2</label>
</body>

Upvotes: 1

Sinus tentaclemonster
Sinus tentaclemonster

Reputation: 538

You seem to be trying to replicate the default radio button behaviour. Set a name="foo" attribute on your <input>s and they'll form a select-only-one group for you.

Upvotes: 1

Related Questions