当前位置: 代码迷 >> Web前端 >> select 框的有关问题
  详细解决方案

select 框的有关问题

热度:83   发布时间:2012-11-23 22:54:33.0
【原创】select 框的问题
select有多种问题,我集中总结分为一下3种
一.显示:

例如:
<select size="4" name="fruit" id="fruit" multiple="multiple">
  <option value="">全部</option> 
  <option value="1">苹果</option> 
  <option value="2">梨</option> 
  <option value="3">桃子</option> 
  <option value="4">香蕉</option> 
  <option value="5">菠萝</option> 
</select>

select标签上有 multiple 属性表示可以多选,如果不多选而是单选,直接去掉该属性,可以通过style="width:xx;height:xx;"来控制select的大小(xxpx或者xx%)

二.选择:
首先定义一个变量
var selectObj = document.getElementById('fruit');


1.没有选项的情况
selectObj.options[0] == null;

2.有选项的情况            
没选中
selectObj.options.selectedIndex<0
                                          
选中(top)   
selectOjb.options.selectedIndex==0
选    中(bottom)
selectOjb.options.selectedIndex == selectOjb.options.length-1

三.传值,取值:(当form提交之后)
单选取值:后台直接通过request.getParameter("fruit") 就可以得到了

多选取值:
思路:
1定义一个隐藏域id='hiddenFruit'
2通过一个JS方法把select框中的每一个选项的值遍例取得放进隐藏域 通过"&amp;"分开
3.后台通过request.getParameter("hiddenFruit")得到一个String串,通过String.split("&")得到一个String数组,遍例String数组,得到每一个元素,就是select框中的每一个选项的值。

代码片段:
<form id='fruitForm' action='' method=''>
   <input type="hidden" id="fruitValue" value="">
   <input type="hidden" id="fruitText" value="">
</form>

<script> 
<!--  
function save() {
    var selectObj = document.getElementById('fruit');
    var ValObj = document.getElementById('fruitValue');
    var TextObj = document.getElementById('fruitText'); 
    for(var i=0; i<selectObj.options.length; i++){
        ValObj.value += selectObj[i].value + "&";
        TextObj.text += selectObj[i].text + "&";
    }
    var form = document.getElementById('fruitForm');
    form.action = "xx.do"
    form.submit();
}
//-->
</script>

String allFruitVal = request.getParameter("fruitValue");
String fruitValue [] = allFruitVal.split("&");
String allFruitText = request.getParameter("fruitText");
String fruitText [] = allFruitText.split("&");

  相关解决方案