常用Javascript表单取值方法
一.常用表单基本取值方法(frm为表单名称,TextBox1为控件ID,以文本框为例,html控件与web服务器控件是一样的)
1.frm.TextBox1.value
2.vartxt=document.all.TextBox1;
txt.value
3.vartxt=document.all["TextBox1"];
txt.value
4.document.getElementById("TextBox1");
二.
1.html复选框(name相同)
表单:<inputid="Checkbox1"type="checkbox"name="chk"value="123"/>sss
<inputid="Checkbox2"type="checkbox"name="chk"value="456"/>aaa
<inputid="Checkbox3"type="checkbox"name="chk"value="789"/>bbb
实现功能:遍历html复选框,得到所选中项
varoChks=document.all.chk;
for(vari=0;i<oChks.length;i++)
{
if(oChks[i].checked)
alert(oChks[i].value);
}
2.html单选框(name相同)
表单:<inputid="Radio1"type="radio"name="rad"value="123"/>123
<inputid="Radio2"type="radio"name="rad"value="456"/>456
实现功能:遍历html复选框,得到所选中项
代码同html复选框
3.html下拉列表框
表单:<selectid="Select1"multiple>
<optionvalue=1>1</option>
<optionvalue=2>2</option>
</select>
实现功能:
3.1得到所选中项的text和value值(选择一项)
varselDrp=document.all.Select1;
alert(selDrp.options[selDrp.selectedIndex].text);
alert(selDrp.options[selDrp.selectedIndex].value);
3.2得到所选中项的text和value值(选择多项)
for(varj=0;j<selDrp.options.length;j++)
{
if(selDrp.options[j].selected)
{
alert(selDrp.options[j].value);
}
}
4.DropDownList控件与ListBox控件
实现功能:得到所选中项的text和value值
代码同html下拉列表框
5.CheckBoxList控件
实现功能:得到所选中项的text
代码:
varchklist=document.all("CheckBoxList1");
vari=0;
for(i=0;i<chklist.rows.length;i++)
{
varname="CheckBoxList1_"+i;
vartmpChecked=document.all[name].checked;
if(tmpChecked)
{
alert(document.all[name].parentElement.innerText);
}
}
function clearMateriel(obj)
{
//全部选中
if(obj=="all")
{
for(var i=0;i<document.getElementById('cblMateriel').getElementsByTagName("input").length;i++)
{
document.getElementById('cblMateriel_'+i).checked =true;
}
}
//清除
else if(obj=="none")
{
for(var i=0;i<document.getElementById('cblMateriel').getElementsByTagName("input").length;i++)
{
document.getElementById('cblMateriel_'+i).checked =false;
}
}
//反选
else if(obj=="reverse")
{
for(var i=0;i<document.getElementById('cblMateriel').getElementsByTagName("input").length;i++)
{
if(document.getElementById('cblMateriel_'+i).checked)
document.getElementById('cblMateriel_'+i).checked =false;
else
document.getElementById('cblMateriel_'+i).checked =true;
}
}
}