表单在开发过程中是最常见的之一,先来个基本的
function YZ()
{
if (document.frm.username.value == "")
{
alert("用户名不能为空!");
document.frm.username.focus();
return false;
}
if (document.frm.pwd.value == "") {
alert("密码不能为空!");
document.frm.pwd.focus();
return false;
}
return true;
}
注意事项:onsubmit()是form所特有的,在表单提交之前执行,通常来加个 return 来进行验证,通过则提交,不通过则阻止默认的提交事件。
第二点我发现,对于表单html控件,在获得他们的元素对象的时候,可以通过其name属性来获得,比如input控件,但是不能跳过form的name,如:document.username.value是错误的,正确的是: document.frm.username.value
第三点:我发现当是get请求的时候,点击提交后,地址栏居然把submit类型的input也当做参数传过去了
http://test.ds.net/html/index2.html?username=1&pwd=1&confirm=%E6%8F%90%E4%BA%A4 好奇怪啊
下面看一个变淡验证的例子
.status1 {
background: gray;
}
.status2 {
background: yellow;
}
.status3 {
background: red;
}
.status4 {
background: green;
}
var GetSibling = function (obj) {
while (true) {
if (obj.nextSibling.nodeName != "SPAN") {
obj = obj.nextSibling;
}
else {
return obj.nextSibling;
}
}
}
window.onload = function () {
var username = document.getElementsByName("username")[0];
var userspan = GetSibling(username);
username.onfocus = function () {
userspan.innerText = "用户名长度在2-20之间";
userspan.className = "status2";
}
username.onblur = function () {
if (username.value.match(/^\S*$/) && username.value.length >= 2 && username.value.length <= 20) {
userspan.innerText = "正确";
userspan.className = "status4";
}
else {
userspan.innerText = "用户名格式不正确";
userspan.className = "status3";
}
}
}