表单的基础知识
在HTML中,表单用<form>元素来表示,在JavaScript中,表单用HTMLFormElement来表示,HTMLFormElement继承了HTMLElement。
获取表单的引用
取得表单的引用有多种方式,常见的就是通过ID来获取元素引用。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<form id="form1" name="form" action="" method="get">
<input id="input0" type="text"> <br>
<input id="input1" type="submit" value="提交">
</form>
<script>
/* 在此处书写javascript代码 */
//通过ID获取form元素
var form1 = document.getElementById("from1");
/*
通过document.forms获取所有表单,forms[0]为第一个表单
var firstForm = document.forms[0];
var myFrom = document.forms["form"]; //获取页面中名称为“form”的表单
*/
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<form id="form1" name="form" action="" method="get">
<input id="input0" type="text"> <br>
<input id="input1" type="submit" value="提交">
</form>
<script>
/* 在此处书写javascript代码 */
//通过ID获取form元素
//var form1 = document.getElementById("from1");
//通过document.forms获取所有表单,forms[0]为第一个表单
var firstForm = document.forms[0];
// var myFrom = document.forms["form"]; //获取页面中名称为“form”的表单
</script>
</body>
</html>
注:可以同时为表单指定ID和name。它们的值不一定相同。
提交表单
当用户单击提交按钮或图像按钮时,就会提交表单。使用<input>或<button>都可以定义按钮。使用<input>时,其type属性值为"submit",使用图像按钮提交表单时,<input>的type属性值为"image",src属性值为图像的路径。
当<input>的type属性为"submit"时,
<input id="input1" type="submit" value="提交">
当<input>的type属性为"image"时,
<input id="imasub" type="image" src="smile.gif">
<button id="butt">确定</button>
在JavaScript中编程调用submit()也能提交表单,这种方法无需包含按钮也能向服务器提交表单数据。
<body>
<form id="myForm" action="php.php" method="get">