在body中就建立form,完善基本的框架
<form name="form1">
<p>姓名:<input type="text" name="firstname" id="name"><br></p>
<p>密码:<input type="password" name="word" id="word"><br>
<p>性别:<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女<br>
<p>爱吃的水果:<input type="checkbox" name="fruit" value="苹果">苹果
<input type="checkbox" name="fruit" value="香蕉">香蕉
<input type="checkbox" name="fruit" value="橘子">橘子
<input type="checkbox" name="fruit" value="芒果">芒果<br>
<p>兴趣爱好:<select name="hobby"id="hobby">
<option value="运动">运动</option>
<option value="看书">看书</option>
<option value="游戏">游戏</option>
<option value="潜水">潜水</option>
</select><br>
<p><input type="button" value="提交" onclick="get_value()">
</form>
基本框架如下
其中包括html中文本框,密码框,多选单选框等的代码的运用,重点在如何在alert中显示自己所选(所填)内容
获取html中的数据
首先在<input type="button" value="提交" οnclick="get_value()">建立函数
在<script>中对函数进行操作
<script type="text/javascript">
function get_value(){
var name=document.getElementById("name");
var word=document.getElementById("word");
var sex=document.form1.sex;
var fruit=document.form1.fruit;
var s="";
for(var i=0;i<fruit.length;i++)//获取复选框的值
if (fruit[i].checked==true) {//直至没有选中跳出
s=s+fruit[i].value;
}
var hobby=document.getElementById("hobby")//获取列表框的值
alert ('姓名:'+name.value +'\n'
+'密码:'+word.value+'\n'+'性别:'+sex.value+'\n'+'爱吃的水果:'+s+'\n'+
'爱好:'+hobby.value);
}
</script>
很容易发现,文本框、密码框、单选框(性别)以及单选下拉列表框等只有一个确定的值的用 document.getElementById就可以确定其值,而多选框如上,则需要使用for循环来确定
最后在 alert中输入自己所选(所填)的数据需要如下显示:
则在alert中需要用+以及'\n'来进行连接和另起一行(最后显示的页面就如上方)
alert ('姓名:'+name.value +'\n'
+'密码:'+word.value+'\n'+'性别:'+sex.value+'\n'+'爱吃的水果:'+s+'\n'+
'爱好:'+hobby.value);