1

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>
2
  • 1
    What do you want exactly ? Commented Jan 11, 2020 at 22:36
  • You can't "set a() to #j1". You mean "set #j1 to use a()", right? Commented Jan 11, 2020 at 22:46

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's it! I forgot to use the name attribute, and I tried to replicate it with JavaScript. Thank you!
Glad I could help! Please mark the question as answered, then. :)
1

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>

1 Comment

Thank you for your contribution. I am just starting using radio buttons and JavaScript and because I left out the name attribute of the inputs, I tried to simulate it with JavaScript. a() and b() worked fine, but I tried to merge them to c() and this is wehere it all went awry. In any case, thank you for your input :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.