用javascript操作表单和操作DOM一样,在html中提供了以下几种表单输入控件:

  • 文本框<input type="text">用于文本输入;
  • 密码框<input type="password">用于密码输入;
  • 单选框<input type="radio">用于单选一项;
  • 复选框<select>用于多项选择;

Html5中也给我们提供了许多方便的新控件:color date email range url等。

下面是js中最基本的两种表单提交操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
方式一
html:
<form id="form1">
<input type="text" id="username" name="username" />
<input type="password" name="password" id="pasd"/>
<input type="button" name="btn" id="btn" value="提交" onclick="sbmit()" />
</form>

javascript:
<script>
var form1 = document.getElementById(form1);
//TODO...
form1.submit();
//总结:利用按钮点击调用函数进行提交 在函数中获取表单对象 调用表单的submit()进行提交
</script>

方式二
html:
<form id="form2" method="post" onsubmit="return onsbmit">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="pasd" />
<input type="submit" name="submit" />
</form>

javascript:
<script>
function onsbmit(){
var form2 = document.getElementById("form2");
var psd = document.getElementById("pasd");
psd_val = toMD5(psd.value);//MD5加密
return true;
}
//总结:利用submit类型的按钮进行提交 利用form的onsubmit属性return函数 如果函数返回true则提交 返回false则不提交
</script>

注意:当一个表单包含<input type="file">的时候,表单的enctype属性必须为multipart/form-data,method必须为post,浏览器才能以multipart/form-data的形式提交数据,同时里面的input必须指定name属性,不然的话该项数据不提交。