(三)JavaScript关于浏览器--操作表单

(三)JavaScript关于浏览器--操作表单

三、操作表单

表单本身也是一个DOM树;复习下HTML表单控件:

<input type="text" name=””value=””/>,用于输入文本

<input type="password"name="password">,用于输入密码

<input type="hidden"/>,用户不可见,但表单提交时会把隐藏文本发送到服务器

<input type="radio"checked="checked" name="Sex" value="boy">男</input>,单选

<input type="radio"name="Sex" value="girl">女</input>,单选,传递的是value

<input type="checkbox"name="cb1">swiming</input>,复选框,传递的是value

<input type="checkbox"name="cb2">running</input>,复选框

<select name=””>

<option value=”” selected ="selected">1</option>

<option value=””>2</option>

</select>,下拉列表

<textarea rows="10"cols="30">,文本域,行,列

<input type="button"value="Hello world!">,按钮type=”submit”为提交按钮reset重置

<fieldset>

   <legend>健康信息</legend>

    身高:<inputtype="text" />

    体重:<inputtype="text" />

 </fieldset>,把一些数据框起来了

<input type="color"value="#ff0000">,跳出选择颜色的框框,设置颜色


1. 获取表单元素的值,并更新它的值

<html>
<body>
<input type="text" id="email" value="123">
<script>
document.getElementById('email').value = 'aaaaa';
</script>
</body>
</html>
2.表单提交

表单提交通过submit;主要是通过事件触发submit,(会先触发onsubmit和onclick)然后提交表单到action=”地址”。以下几种操作会触发submit:

1. 输入框中回车;

2.或点击type为submit的按钮(button默认是submit)

3.点击type为image的也会触发

4.也能通过form.action(‘地址’);

<html>
<head>
<meta charset="UTF-8">	
<title>Insert title here</title>
<script type="text/javascript">	
    function checkForm() {
        var name=document.getElementById("fid").value;
        if(name==""){
    	    alert('不能为空!');
    	    return false;
        }
        else{    	  
            form1.action='http://baidu.com';//把表单提交到
            return true;// 继续下一步:
        } 
     } 
</script>
</head>
<body>
	<form  method="post"  action="" name="form1" id="form-6" onsubmit="return checkForm();">
		<input type="text" id="fid" name="hehe" value="" />
		<input type="submit" name="button" value="提交" />
	</form>
</body>
</html>

5.直接用form.submit();提交,是要设置好action

<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="http://baidu.com" method="post" id="test-form" onsubmit="return hanshu();">
    <input type="text" name="test" id="test">
    <input type="submit" name="button" value="提交" />
</form>
<script>
function hanshu() {
    var text = document.getElementById('test').value;
    if(text==""){
    	alert('bukong');
    	return false;
    }
    else{
    form.submit();// 提交form:
    }
}
</script>
</body>
</html>

注意要return true来告诉浏览器继续提交,如果return false,浏览器将不会继续提交form,这种情况通常对应用户输入有误,提示用户错误信息后终止提交form。

有的时候把<input>中口令由明文变为MD5:
function checkForm() {
    var pwd = document.getElementById('password');
    pwd.value = toMD5(pwd.value); // 把用户输入的明文变为MD5:
    return true;   // 继续下一步:
}



猜你喜欢

转载自blog.csdn.net/qq_35418250/article/details/77892245