admin管理员组

文章数量:1278789

I have two radio buttons. When I click on one, the other should bee unchecked, and vice versa.

The code I've produced so far is not working:

<input type="radio" id="rbdemail" onclick="chekrbdclick()" checked="checked" />
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick()" />

function chekrbdclick() 
{
  // How to manage here?
}

I have two radio buttons. When I click on one, the other should bee unchecked, and vice versa.

The code I've produced so far is not working:

<input type="radio" id="rbdemail" onclick="chekrbdclick()" checked="checked" />
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick()" />

function chekrbdclick() 
{
  // How to manage here?
}
Share Improve this question edited Feb 22, 2022 at 13:17 user229044 240k41 gold badges344 silver badges346 bronze badges asked Dec 10, 2015 at 5:06 amitamit 4495 gold badges8 silver badges21 bronze badges 1
  • 7 Use same name to both radio buttons, there's no need of using JavaScript – Tushar Commented Dec 10, 2015 at 5:06
Add a ment  | 

3 Answers 3

Reset to default 7

Simple, just use a 'name' property with the same value for both elements:

<html>
<body>

<form>
  <input type="radio" name="size" value="small" checked> Small
  <br>
  <input type="radio" name="size" value="large"> Large
</form> 

</body>
</html>

hope it helps

<form>
  <label>
    <input type="radio" name="size" value="small" checked> Small
  </label>
  <br>
  <label>
    <input type="radio" name="size" value="large"> Large
  </label>
</form>

Give them a name attribute with mon value like size, and it will work. For best practice, you can place your input tag inside a label tag, so that, even if your user clicks on the text beside the button (ie on "Small" or "Large"), the respective radio button gets selected.

The perfect answer is above answered ,but I wanna share you how it can work by javascript ,this is javascript work (not standard answer) ....

    <input type="radio" id="rbdemail" onclick="chekrbdclick(0)" checked="checked" value="Small" />Small<br>
    <input type="radio" id="rbdsitelnk" onclick="chekrbdclick(1)" value="Large" />Large
    <script>
    function chekrbdclick(n) 
    {
      var small = document.getElementById('rbdemail');
      var large = document.getElementById('rbdsitelnk');
     if(n === 0){  
      small.checked = true;  
      large.checked = false;
     }
     else {   
      small.checked = false;  
      large.checked = true;
     }
    }
    </script>

本文标签: javascriptHow to do toggle two mutually exclusive radio buttons in HTMLStack Overflow