javascript在表单里的处理

事件

绑定事件
element.attachEvent(eventName,eventHandler,useCapture)
element.addEventListener(eventName,eventHandler,useCapture)
useCapture表示处理模式是否使用捕获模式

element.addEventListener("onclick",func,false)

event对象属性
窗口的x坐标:clientX
窗口的y坐标:clientY
屏幕的x坐标:screenX
屏幕的y坐标:screenY
鼠标按键:button
键盘按键:keyCode
按下shift键:shiftKey
按下alt键:altKey
按下ctrl键:ctrlKey

1)
<script language="javascript" type="text/javascript">
<!--
function asy(){
alert("hello");
}
document.onclick=say;
-->
</script>

2)
<textarea id="" name="content"></textarea>

<script language="javascript" type="text/javascript">
<!--
var txt=document.getElementById("content");
txt.onkeydown=function(evt){
evt=evt?evt:window.event;//兼容浏览器
if(evt.ctrlKey &&13==evt.keyCode)thie.form.submit();
}
-->
</script>

表单

获得表单
var myform=document.forms["myform"];
var myform=document.fors[0];

Form对象事件
onsubmit在表单提交之前触发
onreset在表单被重置之前触发

引用表单元素
var element=theForm.elements[idex];
var element=theForm.elements[elementName];

遍历一个表单中的所有表单域
for(var i=0;i<theForm.elements.length;i++){
   if("checkbox"==theForm.elements[i].type){}
}

表单域的通用属性
1)创建只读(不可用)表单域
element.disabled=true;
element.disabled=false;

2)获取表单域的值
value


表单域的通用方法
表单域获得焦点:focus()
表单域失去焦点:blur()

表单域的通用事件
onFocus:获得焦点时,产生该事件
OnBlur:失去焦点时,产生该事件
--Onselect:文字被加亮显示后(选择),产生该文件。
onchange:表单域的值改变时

onclick:键盘单击
onkeydown:键盘按下
onkeyup:键盘松开
onkeypress:键盘按下松开

onmouseover:鼠标移上
onmouseout:鼠标移出
onmousedown:鼠标按下
onmouseup:鼠标松开

文本域
获取和设置文本域的内容:value
   theform.elements["sum"].value;

获得HTML标记中的value值:defaultValue

选中文本:select
<input type="text" name="" onfocus="this.select()">

复选框
当复选框被选中时checked返回true
document.forms[0].elements[i].checked

单选按钮
checked属性来获取或设置单选按钮的状态
<input type="radio" name="sex" value="famale" checked>

下拉列表框
使用value属性获取和设置下拉列表框的值
使用length属性获取选项个数
使用selectedIndex属性获取当前选项的索引
使用options属性获取选项集合
option对象的value属性:<option>标记中所指定的值
option对象的text属性:显示于界面中的文本,<option>和</option>间的
option对象的selected属性:选中和未选中
select对象的onchange事件:选中项发生变化时
为select对象添加一个选项:someselect.options[slt.length]=new Option(value,text);
从select对象中删除一个选项:someselect.option[i]=null;
清空select对象:someselect.length=0;
替换一个选项:someselect.options[i]=new option("apple","apple");

表单验证
1)<input type="submit" onclick="return validade()">
2)<form action=""method="" onsubmit="return validate()">

验证文本中否为空:
if(tbusername.value.length==0){
alert("");
return false;
}
验证下拉列表是否为空:
if(sltcity.selectIndex==0){
alert("");
return false;
}
原文地址:https://www.cnblogs.com/Excellent/p/1242271.html