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

选择框(select)添加或者减少选项(option)操作的js代码

选择框(select)添加或者减少选项(option)操作的js代码如下所示:

?

function changeToSelect()
{
      var selected = document.forms[0].enterTypesSelected;
    var noSelected = document.forms[0].enterTypesNOSelect;
    var selectedColl = selected.options;
    var noSelectedColl = noSelected.options;
    var enterTypes = document.forms[0].enterTypes.value;
    
    var tLen = noSelectedColl.selectedIndex;
    if(tLen > -1)
    {
        var tValue = noSelectedColl.options[tLen].value;
        var tText =  noSelectedColl.options[tLen].text;
       
       addOption(selectedColl,tValue,tText); 
       removeOption(noSelectedColl,tLen);
   }
   else
   {
       alert("请从类别列表中选择类别!");
       return;
   }
}


function changeToNoSelect()
{
    var selected = document.forms[0].enterTypesSelected;
    var noSelected = document.forms[0].enterTypesNOSelect;
    var selectedColl = selected.options;
    var noSelectedColl = noSelected.options;
    
    var tLen = selected.selectedIndex;
    if(tLen > -1)
    {
        var tValue = selected.options[tLen].value;
        var tText =  selected.options[tLen].text;
    
       addOption(noSelectedColl,tValue,tText); 
       removeOption(selectedColl,tLen);
   }
   else
   {
       alert("请从类别列表中选择类别!");
       return;
   }
}

function addOption(colls,value,text)
{
    colls.add(createOption(text,value));
    colls.selectedIndex = colls.selectedIndex.length-1;
}
function createOption(text,value)
{
    return new Option(text,value);
}
function removeOption(colls,index)
{
    if(index >-1)
    {
        colls.remove(index);
        colls.selectedIndex = colls.selectedIndex.length-1;
    }
}

?页面HTML代码如下所示:

?

 <table width="65%"  border="0" cellspacing="0" cellpadding="0">	
			<tr class="tdbg">
				<td height="22" width="37%" bgcolor="#FFFFFF" class="PL6"><strong>
				待选择类别:</strong></td>
				<td width="14%" bgcolor="#FFFFFF">&nbsp;</td>
				<td width="49%" bgcolor="#FFFFFF" class="PL6"><strong>已选中类别:</strong></td>
			</tr>
			<tr class="tdbg">
				<td bgcolor="#FFFFFF">
                <select name="enterTypesNOSelect" multiple style="width:150px;overflow:auto" size="5">
                    <option value="2">物业子系统</option>
                    <option value="3">商家子系统</option>
                    <option value="4">管委会子系统</option>
                    <option value="5">商会子系统</option>
				      </select>
       </td>
				<td bgcolor="#FFFFFF"><a href="#" onClick="changeToSelect()"><img src="images/icon/icon_add_toselected.gif" border="0"></a>
					<p><a href="#" onClick="changeToNoSelect()"><img src="images/icon/icon_add_toselect.gif" border="0"></a></td>
				<td height="22" nowrap bgcolor="#FFFFFF">
				<select name="enterTypesSelected" multiple style="width:150px;overflow:auto" size="5">
             <option value="1">企业子系统</option>                   
				</select>
				</td>
			</tr>	
</table>

?页面的最终效果如下所示:

?


?

?

?

?

?

?