【问题标题】:Radio buttons in HTML form not working properlyHTML 表单中的单选按钮无法正常工作
【发布时间】:2021-11-21 03:45:25
【问题描述】:
我正在学习 Javascript 和 HTML 中的表单,我知道单选按钮。但问题是当我编写 3 个单选按钮进行测试时,不知何故它不起作用,当我选中“1”(它是一个名称)并选择另一个像“2”这样的单选按钮时,它并没有取消选中“ 1”!我的浏览器有问题,还是我的代码有问题?我使用的是 Microsoft Edge 浏览器,这是我的代码:
<form>
<label for="html">This one is Html </label>
<input type="radio" name="html" id="html" value="HTML">
<br>
<label for="css">This one is Css</label>
<input type="radio" name="css" id="css" value="CSS">
<br>
<label for="javscript">This one is Javascript</label>
<input type="radio" name="javscript" id="javascript" value="JAVASCRIPT">
</form>
有人知道我的问题吗?
【问题讨论】:
标签:
javascript
html
forms
radio-button
【解决方案1】:
name 属性作为一个组。所以如果你在单选按钮上设置相同的name,它们就在同一个组中。
<form>
<label for="html">This one is Html </label>
<input type="radio" name="group1" id="html" value="HTML">
<br>
<label for="css">This one is Css</label>
<input type="radio" name="group1" id="css" value="CSS">
<br>
<label for="javscript">This one is Javascript</label>
<input type="radio" name="group1" id="javascript" value="JAVASCRIPT">
</form>
【解决方案2】:
这很简单,你只需要为每个组使用相同的name,这里我使用codetype:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<label for="html">This one is Html </label>
<input type="radio" name="codetype" id="html" value="HTML">
<br>
<label for="css">This one is Css</label>
<input type="radio" name="codetype" id="css" value="CSS">
<br>
<label for="javscript">This one is Javascript</label>
<input type="radio" name="codetype" id="javascript" value="JAVASCRIPT">
</form>
</body>
</html>
【解决方案3】:
请您当时可以使用单选按钮,所有单选按钮name 设置相同,然后您选择一个单选按钮。
<form>
<label for="html">This one is Html </label>
<input type="radio" name="skill" id="html" value="HTML">
<br>
<label for="css">This one is Css</label>
<input type="radio" name="skill" id="css" value="CSS">
<br>
<label for="javscript">This one is Javascript</label>
<input type="radio" name="skill" id="javascript" value="JAVASCRIPT">
</form>
【解决方案4】:
只需为每个组使用相同的名称属性值即可。
<form>
<label for="html">This one is Html </label>
<input type="radio" name="radio_button" id="html" value="HTML">
<br>
<label for="css">This one is Css</label>
<input type="radio" name="radio_button" id="css" value="CSS">
<br>
<label for="javscript">This one is Javascript</label>
<input type="radio" name="radio_button" id="javascript" value="JAVASCRIPT">
</form>