Search code examples
javascripthtmlradio-buttonradiobuttonlist

Radio button malfunctioning when used inside label tag


i am working on html and CSS. i have to add 5 radio buttons to my page and i have added within <label> tag. but when i look for the page. it shows all the radio buttons selected and also i am unable to unselect it. the thing is i need only one radio button selected at a time. here is my code.

<label class="radio"><input type="radio"> Pepse</label> 
<label class="radio"><input type="radio"> Coke</label> 
<label class="radio"><input type="radio">Mirinda</label>
<label class="radio"><input type="radio">Maaza </label>

Solution

  • radio buttons require a common name. If you don't give them a name attribute, each radio button essentially becomes a one-way checkbox. You can select them, but you can't UNselect them.

    <input type="radio" name="foo" value="1" />
    <input type="radio" name="foo" value="2" />
    
    <input type="radio" value="3" />
    

    In this case, the two foo radio buttons will be linked internally because they are both named the same, but the one with value 3 will be completely independent and act as your are.