<input type="radio" />
同单行文本框和密码框一样,单选按钮要想被正确提交,也必须设置 name 属性。除了 name 属性之外,单选按钮还有几个其它属性,我们来看一下。其它属性 | 说明 |
---|---|
checked | 用来规定在页面加载时应该被预先选定的 input 元素。 |
value | 用来定义被选中时发送到服务器的值。同一组中每个按钮的值应该不同,这样服务器才能辨别提交的是哪一项。 |
id | 规定 HTML 元素的唯一 id。id 值在整个页面是唯一的,不会重复。 |
<form action="http://vip.biancheng.net/login.php" method="post" name="formName"> 性别:<input type="radio" name="girl" checked="checked">女 <input type="radio" name="boy" checked="checked">男 </form>运行结果如图所示:
checked="checked"
属性,其实还有一个原因,两个单选按钮的 name 属性值不同也会产生这样的结果。
注意:当 type 属性值为 radio 时,name 属性值必须保持一致。本例只是为了演示问题才会为所有按钮加checked="checked"
属性,在实际开发中不会这样写。checked="checked"
可以简写为 checked。
<form action="http://vip.biancheng.net/login.php" method="post" name="formName"> 性别:<input type="radio" name="sex" checked>女 <input type="radio" name="sex" checked>男 </form>运行结果如图所示:
<form action="http://vip.biancheng.net/login.php" method="post" name="formName"> 性别:<input type="radio" name="sex" value="girl">女 <input type="radio" name="sex" value="boy" checked="checked">男 </form>运行效果如图所示:
<form action="http://vip.biancheng.net/login.php" method="post" name="formName"> 性别:<input type="radio" name="girl" value="girl" id="girl"><label for="girl">女</label> <input type="radio" name="girl" value="boy" id="boy" checked="checked"><label for="boy">男</label> </form>通过以上代码可以发现,<label> 标签中的 for 属性与 <input> 元素的 id 属性值相同,我们可以说它们之间进行了一个绑定。那么 <label> 标签到底是用来做什么的呢?
我们建议每个单选按钮都和 <label> 标签配合使用,一是为了用户体验,二是为了在后期使用 JavaScript 语言操作数据时更方便。
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有