html 表单与表单元素
1 表单的作用
表单用于接受用户输入的数据,提交至服务器处理。
当用户输入帐号密码,点击登录按钮,会提交至服务端处理,服务端处理完后进行响应。
后端常用技术:JAVA等,这里仅介绍HTML,无法完整展示表单的作用,仅模拟以便大家理解。
2 表单form
基本语法
<form action="地址">
…
</form>
表单里通常含有文本框与提交按钮;
点击提交按钮,会把文本框等表单元素的数据提交到action属于指定的地址。
示例:模拟登录,直接跳转到静态处理页面。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" >
<title>html 表单 例子 | 关关教程</title>
</head>
<body>
<form action="https://tuto.dushare.cn">
帐号:<input type="text" > <br>
密码:<input type="password" > <br>
<button type="submit">登录</button>
</form>
</body>
</html>
<input type="text" > 普通文本框;
<input type="password" > 密码框;
<button type="submit">登录</button> 提交按钮。
3 常用表单控件
常用表单控件 | 说明 |
---|---|
<input type="text"> | 文本框。 属性value:文本框的值。 |
<input type="password"> | 密码框。 属性value:密码框的值。 |
<input type="checkbox"> | 复选框。 属性checked:只需属性名,表示选中。 |
<input type="radio"> | 单选框。name相同的多个单选项归为一组,每组只能选中一个。 属性checked:选中。 |
<select> <option>项内容</option> … </select> | 下拉列表框。每一项对应一个option标签。 option的selected属性:只需属性名,表示选中。 |
<textarea></textarea> | 文本域,即多行文本框。 内容直接放在标签体里。 |
<button type="button"></button> | 普通按钮。 |
<button type="submit"></button> | 提交按钮。 |
<button type="reset"></button> | 重置按钮。form里各表单控件的数据会恢复到打开时的数据。 |
4 示例
用户注册页面
代码
<!-- 表单控件 -->
<form action="https://tuto.dushare.cn">
用户账号:<input type="text" value="dushare"> <button type="button">校验是否存在</button><br>
密码:<input type="password" value="123456"> <br>
<input type="checkbox" checked>同意协议 <br>
性别:<input type="radio" name="gender" checked>男 <input type="radio" name="gender">女 <br>
婚否:<input type="radio" name="marry" checked>已婚 <input type="radio" name="marry">未婚 <br>
省份:<select>
<option>北京</option>
<option selected>上海</option>
<option>广东</option>
</select> <br>
个人简介:<br>
<textarea>关关教程</textarea> <br>
<button type="submit">注册</button> <br>
<button type="reset">重置</button> <br>
</form>
5 label标签
当点击label内的文字,焦点会自动移到for属性指定的控件。
基本使用步骤
第1步:为表单控件定义id
<标签 id="控件ID" >
第2步:定义label,通过for属性指定表单控件
<label for="控件ID ">文字</label>
示例代码
<!-- label标签 -->
<form action="https://tuto.dushare.cn">
<label for="userCode">用户账号:</label><input id="userCode" type="text" value="dushare"> <br>
<label for="password">密码:</label><input id="password" type="password" value="123456"> <br>
<input id="agree" type="checkbox" checked><label for="agree" >同意协议</label> <br>
<button type="submit">注册</button> <br>
</form>
当鼠标点击文字"用户帐号"时,焦点会自动移到后面的文本框。