JS獲取form表單

本文實例講述了js獲取form的方法。分享給大家供大家參考。具體如下:

先來看下面代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<scirpy>
window.onload=function(){
   var f1=document.f1;
   var f2=document.forms[1];
 alert(f2.id);
  var f3=document.forms['f1'];
}
</script>
</head>
<body>
<form id="f1" value="f1"></from>
<from id="f2" value="f2"></form>
</body>
</html>

操作表單:

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
<html>
 <head>
 <script>
  function checkform(f){
  var uname=f.username;
  var pwd=f.password;
  if(uname.value.length<4){
  alert('用戶長度必須大於4');
  return false;
  }
  if(pwd.value.length!=6){
  alert('用戶密碼必須大於 6位');
  return false;
  }
  return true;
  }
 </script>
 </head>
 <body>
 <form id="f1" name="f1" method="post" action=""
 onsubmit="return checkform(this)">
   <input name="username" value="" /></br>
  <input name="password" value="" /></br>
  <input type="button" value="提交" /> 
 </form>
 </body>
</html>

js操作form的三種方式:

1. 利用表單在文檔中的索引或表單的name屬性來引用表單

複製代碼 代碼如下:
document.forms[i]  //得到頁面中的第i個表單
document.forms[fromName] //得到頁面中相應name的表單

2. 利用表單的id屬性

複製代碼 代碼如下:
document.getElementById(formId);

3.

複製代碼 代碼如下:
document.formName;//最爲常用的一種方式

希望本文所述對大家的javascript程序設計有所幫助。

 

轉載地址:http://www.jb51.net/article/65578.htm

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章