HTML控件——select常用操作

select常用操作:追加,移除,選擇。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>HTML-select-操作</title>
</head>
<body>
    <select id="s1" name="s1" multiple="multiple">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    <br />
    <input id="btnAppend" type="button" value="Append" onclick="return btnAppend_onclick()" />
    <input id="btnRemove" type="button" value="Remove" language="javascript" onclick="return btnRemove_onclick()" />
    <input id="btnGetText" type="button" value="Get Selected Text" language="javascript"
        onclick="return btnGetText_onclick()" />
</body>


</html>


 

<script type="text/javascript">

// 功能:追加option
// 參數:
//      obj:select control
//      strText:option的文字
//      strValue:item的值
function appendSelectOption(obj,strText,strValue)
{
    
    
    var ctrl = obj;
    var option = new Option(); // 注意:對象Option首字母大寫      
    
    option.text=strText;
    option.value=strValue;
    
    if (isExsitOption(obj,option)) {return;}
    
    ctrl.add(option); // 注意:方法add()首字母大寫
}

// 功能:移除item
// 參數:
//      obj:select control
function removeSelectedOption(obj)
{
    var ctrl = obj;
    var selectedIdx = ctrl.selectedIndex;
    
    //alert(selectedIdx);
    if (selectedIdx==-1)
    {
        alert('Please selected item first!');
        return;
    }
    
    ctrl.remove(selectedIdx)
}

// 功能:移除item
// 參數:
//      obj:select control
//      retType:取option的text or value
function getSelectedOption(obj,retType)
{
    var ctrl = obj;
    var selectedIdx = ctrl.selectedIndex;
    
    //alert(selectedIdx);
    if (selectedIdx==-1)
    {
        alert('Please selected item first!');
        return;
    }
    
    if (retType=='TEXT')    
    alert('selected text is ' + ctrl.options[selectedIdx].text);
    
    if (retType=='VALUE')
    alert('selected value is ' + ctrl.options[selectedIdx].value);
}

function isExsitOption(obj,option)
{
    for(i=0;i<obj.options.length;i++)
    {
        if(obj.options[i].text==option.text)
        {
            alert('this text is exsit!');            
            return true;
        }

        if(obj.options[i].value==option.value)
        {
            alert('this value is exsit!');            
            return true;
        }
    }    
    return false;
}

// 測試——追加option
function btnAppend_onclick() {
    var ctrl = document.getElementById('s1');
    appendSelectOption(ctrl,1,1);
}

// 測試——移除option
function btnRemove_onclick() {
    var ctrl = document.getElementById('s1');
    removeSelectedOption(ctrl);
}

// 測試——取選擇的內容
function btnGetText_onclick() {
    var ctrl = document.getElementById('s1');
    getSelectedOption(ctrl,'TEXT');
}

</script>

posted @ 2010-11-10 16:14  yellowwood  阅读(430)  评论(0编辑  收藏  举报
Never Give UP