2012-09-17 87 views
0

我有一個組合框,它具有一些值,我也有一些值,我從組合框中選擇一個值並進行一些操作並返回選定的值(在會話中設置這些值)。現在我需要自動選擇組合框中會話的值。從動態創建的組合框中刪除重複的值

我按照下面的JavaScript和它工作正常,但它創建了一個重複的值,它是已在組合框中:

function addCombo() { 
    var reportID = '<%=reportid%>'; 
    var reportName = '<%=reportname%>'; 

    var textb = document.getElementById("reportnames"); 

    var option = document.createElement("option"); 
    option.text = reportName; 
    option.value = reportID; 
    option.selected='selected'; 
    try { 
     textb.add(option, null); //Standard 
    }catch(error) { 
     textb.add(option); // IE only 
    } 
    textb.value = ""; 
} 

誰能幫我鑑別?

+0

這個鏈接可以幫助你:http://stackoverflow.com/questions/4590311/set-option-selected-attribute-from-dynamic-created-option – Anoop

回答

0

我還沒有刪除的價值,而我加入如下代碼,它解決了我問題。

function addCombo() { 
    var reportID = '<%=reportid%>'; 
    var options= document.getElementById('reportnames').options; 
    for (var i= 0, n= options.length; i < n ; i++) { 
     if (options[i].value==reportID) { 
      document.getElementById("reportnames").selectedIndex = i; 
      break; 
     } 
    } 
} 
0

明白OK嘗試:

function addCombo() { 
    var reportID = 'aa'; 
    var reportName = 'aa'; 

    var textb = document.getElementById("reportnames"); 
    var option = document.createElement("option"); 

    if (hasValue(textb, reportID)) (function() { 


     // selected attr remove 
     for (var i=textb.options.length-1; i >= 0; i--) (function() { 

      if (textb.options[i].selected == true) (function() { 

       textb.options[i].removeAttribute("selected"); 
      }()); 
     }()); 

     option.text = reportName; 
     option.value = reportID; 

     // selected new option element 
     option.setAttribute("selected", "selected"); 


     try { 
      textb.add(option, null); //Standard 
     } catch(error) { 
      textb.add(option); // IE only 
     }; 

     /* 
     * I do not understand selected added option value "" ?? 
     */ 
     //textb.value = ""; 

     }()); 
}; 

hasValue的功能:

function hasValue(element, value) { 
    var results = true; 

    for (var i=element.options.length-1; i >= 0; i--) (function() { 

     if (element.options[i].value == value) (function() { 
      results = false; 
     }()); 
    }()); 

    return (results); 
}; 

處之泰然..