Javascript操作form中Field Radio Checkbox Select等的代碼

來源:互聯網
上載者:User

<html>
<head>
<title>表單輸入驗證執行個體</title>
<script type="text/javascript">
function validate()
{
var userName=document.forms[0].userName.value;
var password=document.forms[0].password.value;
var rePassword=document.forms[0].rePassword.value;
var test=document.forms[1].test;
//得到選項值
var birth=document.forms[0].birth;
alert(birth.options[birth.selectedIndex].text);
if(test)
{
alert(test.value);
}

//Radio button
var sex=document.getElementsByName("sex");
for(var i=0;i<sex.length;i++)
{
 if(sex[i].checked==true)
 { alert(sex[i].value);}
}
//checkbox 存到數組中
var habit=document.getElementsByName("habit");
var habits=new Array();
for(var i=0;i<habit.length;i++)
{
 if(habit[i].checked==true)
 {
  alert(habit[i].value);
  habits[i]=habit[i].value;
 }
}
for (var j=0;j<habits.length ;j++ )
{
 alert(habits[j]);
}

//定義變數病將表單的值付給變數其中“//”為Javascript中的注釋。
if(userName.length<=0)
alert("使用者名稱不可為空!");
else if(password<=0)
alert("密碼不可為空!");
else if(rePassword<=0)
alert("重新輸入密碼不可為空!");
else if(userName.length<6)
alert("使用者名稱不能小於6位!");
else if(password!=rePassword)
alert("兩次輸入密碼不一致!");
else
{
alert("驗證通過,表單可以提交!");
document.forms[0].submit();
}
}
</script>
</head>
<body>
<form action="" method="post">
使用者名稱:<input type="text" name="userName"></input><br>
密碼:<input type="text" name="password"></input><br>
請重新輸入密碼:<input type="text" name="rePassword"></input><br>
性別:<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女<br>
出生日期:<select name="birth">
<option value="0">--s請選擇--</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
</select>年<br>
興趣:<input name="habit" type="checkbox" value="1">音樂</input>
<input name="habit" type="checkbox" value="2">動漫</input>
<input name="habit" type="checkbox" value="3">電影</input><br>
<input type="button" value="提交" onClick="validate()"></input>
<input type="reset" value="取消"/>
</form>
<form action="" method="post">
 <input type="text" name="test"></input>
</form>
</body>
</html>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.