首页 > 语言 > JavaScript > 正文

JS获取文本框,下拉框,单选框的值的简单实例

2024-05-06 14:29:09
字体:
来源:转载
供稿:网友

1.文本框

1.1 <input type="text" name="test" id="test">

通过var t=document.getElementById("test").value把值赋给变量t,

1.2 当然也可以反过来把已知的变量值赋给文本框,例如:

var m = "5";
document.getElementById("test").value= m;

2.下拉列表框

2.1
<select name="sel" id="sel" onchange="look();">
<option value="1" >11</option>
<option value="2" selected>22</option>
<option value="3">33</option>
</select>

通过var s=document.getElementById("sel").value获取<select>框中选中的值,此处默认选中value="2"的选项,所以赋给变量s 的值是"2",而不是"22",

假如要把<select>中选择的"值"如"3"对应的"文本值"("33")赋给test文本框,可以通过如下方法,
代码如下:
<script language="javascript">

function look(){

      var se =document.getElementById("sel");  
                 var option=se.getElementsByTagName("option");  
                 var str = "" ;  
                 for(var i=0;i<option.length;++i)  
                 {  
                 if(options[i].selected)  
                 {  
                 document.getElementById("test").value = option[i].text;  
                 }  
                 } 

 

 

}

</script>

2.2 将给定的值与<select>框中的值进行比较,如果<select>中的<option>的value值与给定的值相同,则选中它。
代码如下:
var m = "2",

for(var i = 0;i<document.getElementById("sel").length;i++)
         {
          with(document.getElementById("sel").options[i])
                 {
                 if(value == m)
                 {
                 selected = true;

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选