JS获取Select标签选中的值

来源:互联网 发布:现在做淘宝还有前景吗 编辑:程序博客网 时间:2024/04/30 03:53

项目中用到下拉标签<select> 进行来定义范围搜索功能,而灰显提示的内容却是不一样的。需要用到JS获取Select值,来进行判断提示。

  • JavaScript方法
var obj = document.getElementById("控件ID");//获取var index = obj.selectedIndex; // 选中索引var text = obj.options[index].text; // 选中文本var value = obj.options[index].value; // 选中值</span>

  • JQuery方法
$("#testSelect ").get(0).selectedIndex;//索引$('#testSelect option:selected') .val();//选中的值$('#testSelect option:selected').text();//选中的文本</span>

案例:

第一步:这是<select>控件
<select  onchange="change(this)" id="search_name" name="test" > <option value="1">这里是一</option> <option value="2">这里是二</option> <option value="3">这里是三</option></select>
第二步:写js方法(我这里直接用下拉框选项的索引值进行给<input>赋提示信息的值)
function change(s){v = s.options[s.selectedIndex].value if(v==1){ <span style="white-space:pre"></span>document.getElementById("frvalue2").value="提示1" }else{ document.getElementById("frvalue2").value="提示2" }}
第三步:给input设置初始提示值,指定下得,失焦点事件。
<input value="提示内容" <!-- 获得焦点事件 -->onFocus='if (this.value == "提示1" || this.value == "提示2") {this.value ="";this.style.color = "";}'  //清空提示的值<!-- 失去焦点事件 -->onBlur='if (this.value == "")  { var obj = document.getElementById("search_name");var index = obj.selectedIndex;  if(index==0){this.value = "提示1";}else{ this.value = "提示2";} this.style.color = "#ac0820";}'   //获取提示的值<!-- 以下是样式不用管 -->style=" color:#ac0820; font-size:12px;line-height:18px;height:20px; float:left; width:205px;margin-left:0px; margin-top:0px; border:1px solid #fff" type="text" name="frvalue" id="frvalue2"  />
以上例子,仅供参考。写的不是很好。

0 0
原创粉丝点击