2011-10-02 51 views
0

我試圖防止從列表框中打印重複值到標籤,這是我所做的,但顯然它不是正確的,沒有錯誤,但沒有打印出來給我標籤,如果我刪除此行:Javascript +防止從列表框中打印出重複的值來標記

if (arSelected.indexOf(selectBox.option[i].selected == -1)) 

它打印出的值,但顯然每次我點擊,並突出顯示在列表框中的值,它會再打印出來給我的標籤。請提供建議。謝謝!

<select multiple size="8" style="width: 135px" onBlur="selectAl ('QualMemTypeToBox',true)" id="QualMemTypeToBox"></select> 

function selectAll(selectBox, selectAll) { 
     var arSelected = ""; 
     // have we been passed an ID 
     if (typeof selectBox == "string") { 
      selectBox = document.getElementById(selectBox); 
     } 
     // is the select box a multiple select box? 
     if (selectBox.type == "select-multiple") { 
      for (var i = 0; i < selectBox.options.length; i++) { 
       selectBox.options[i].selected = selectAll; 

       if (arSelected.indexOf(selectBox.option[i].selected == -1)) { 

        document.getElementById('<%=uilblDestinationQualMemType.ClientID%>').innerHTML += selectBox.options[i].value + " | "; 
        arSelected += selectBox.options[i].selected; 
       } 
      } 
     } 
    } 

回答

1

嘗試:

function selectAll(selectBox, selectAll) { 
    var arSelected = ""; 
    // have we been passed an ID 
    if (typeof selectBox == "string") { 
     selectBox = document.getElementById(selectBox); 
    } 
    //reset the label every time the function is called 
    document.getElementById('<%=uilblDestinationQualMemType.ClientID%>').innerHTML=""; 

    // is the select box a multiple select box? 
    if (selectBox.type == "select-multiple") { 
     for (var i = 0; i < selectBox.options.length; i++) { 
      selectBox.options[i].selected = selectAll; 
      //make sure you process only items that have been checked 
      //AND you need to track the VALUE of the <option> 
      //NOT the "selected" attribute 
      if (selectBox.options[i].selected && arSelected.indexOf(selectBox.options[i].value) == -1) { 

       document.getElementById('<%=uilblDestinationQualMemType.ClientID%>').innerHTML += selectBox.options[i].value + " | "; 
       //here is where you actually update the variable with the VALUE 
       //of the <option>, not the "selected" attribute 
       arSelected += selectBox.options[i].value; 
      } 
     } 
    } 
} 
+0

感謝您的評論的解釋。有用。 – k80sg