日期:2014-05-16  浏览次数:20343 次

javascript 表单验证(二)
表单验证(二)
一、列表框和组合框
1.访问选项
HTML DOM为每个<select/>定义了options集合,它是控件所有<option/>元素列表
oListbox.options[1].firstChild.nodeValue;//返回display的值
oListbox.options[1].getAttribute("value");//返回value的值
oListbox.options[1].text;//返回display的值
oListbox.options[1].value;//返回value的值
oListbox.options[1].index;//返回索引值
oListbox.options.length;//返回下拉列表长度
oListbox.selectedIndex;//返回选中的索引值

2.获取所有选中项
function getSelectedIndex(oListbox){
var arrIndexs=new Array();
for(var i=0;i<oListbox.options.length;i++){
if(oListbox.options[i].selected){
arrIndexs.push(i);
}
}
return arrIndexs;
}
3.添加选项
function addOptions(oListbox,sName,sValue){
var oOption=document.createElement("option");
oOption.appendChild(document.createTextNode(sName));
if(arguments.length==3){
oOption.setAttribute("value",sValue);
}
oListbox.appendChild(oOption);
}

4.删除选项
oListbox.options[index]=null;//BOM删除
oListbox.remove(index);
5.移动选项
function moveOption(oListboxFrom,oListboxTo,iIndex){
var oOption=oLostbox.options[iIndex];
if(oOption!=null){
oListboxTo.appendChild(oOption);
}
}

5.重新排序选项
function shiftTop(oListbox,iIndex){
if(iIndex>0){
var oOption=oListbox.options[iIndex];
var oPrevOption=oListbox.options[iIndex-1];
oListbox.insertBefore(oOption,oPrevOption);
}
}
function shiftDown(oListbox,iIndex){
if(iIndex<oListbox.options.length-1){
var oOption=oListbox.options[iIndex];
var oNextOption=oListbox.options[iIndex+1];
oListbox.insertBefore(oNextOption,oOption);
}
}

6.自动输入的文本框
function autosuggestMatch(sText,arrValues){
var arrResult=new Array();
if(sText!=""){
for(var i=0;i<arrValues.length;i++){
if(arrValues[i].indexOf(sText)==0){
arrResult.push(arrValues[i]);
}
}
}
return arrResult;
}
function autosuggest(oTextbox,arrValues,sListboxId){
var oListbox=document.getElementById(sListboxId);
ListUtil.clear(oListbox);
var arrMatches=autosuggestMatch(oTextbox.value,arrValues);
for(var i=0;i<arrMatches.length;i++){
ListUtil.add(oListbox,arrMatches[i]);
}
}