2011-08-15 101 views
0

我需要在下面的div中顯示選定的subcatogeries(多),並且在某些情況下我需要關閉從選擇錯誤選擇的div元素框,以便我可以向div中添加和刪除元素(通過上面的選擇框)。需要幫助添加選擇框中的選定項到div(動態添加)

即使我做了類似的代碼,但它不適用於多選。

簡而言之,我需要選擇catogories(多)與關閉按鈕在下面的div。

非常感謝提前。

<script type="text/javascript"> 
function selectlist() { 
    checkboxhome = document.getElementById("check"); 
    catogery = document.getElementById("cat"); 
    value = catogery.options[catogery.selectedIndex].value; 
    checkboxhome.innerHTML = "<br/> <p>" + value + "</p>"; 

} 
</script> 
<body> 
    <form action="#" enctype="multipart/form-data"> 
     <select name="cat" id="cat" onchange="selectlist();" multiple="multiple"> 
      <option>Select subcatogery</option> 
      <option value="fashion">Fashion</option> 
      <option value="jewelry">Jewelry</option> 
      <option value="dresses">dresses</option> 
      <option value="shirts">Shirts</option> 
      <option value="diamonds">Diamonds</option> 
     </select> 
     <div id="check"> 
     </div></form> 
</body> 
</html> 

回答

0

環比option S和檢查,如果他們被選中,是這樣的:

function selectlist() { 
    var checkboxhome = document.getElementById("check"); 
    var category = document.getElementById("cat"); 
    checkboxhome.innerHTML = ''; 
    for (var i = 0; i < category.options.length; i++) { 
     if (category[i].selected) { 
      checkboxhome.innerHTML += "<p>" + category.options[i].value + "</p>"; 
     } 
    } 

} 
+0

非常感謝。但它是否可以通過關閉按鈕獲得按鈕樣式的div元素? ,以及我怎樣才能發送這些div值通過PHP到MySQL?因爲它們動態生成。 – steve

0

這裏是什麼能爲你工作小提琴:http://jsfiddle.net/maniator/W6gnX/

的Javascript:

function selectlist() { 
    checkboxhome = document.getElementById("check"); 
    catogery = document.getElementById("cat"); 
    value = getMultiple(catogery); 
    checkboxhome.innerHTML = "<br/> <p>" + value + "</p>"; 

} 


function getMultiple(ob) 
{ 
    var arSelected = new Array(), length = ob.length, i = 0, indexes = []; 
    while (ob.selectedIndex != -1 && i < length) 
    { 
     if (ob.selectedIndex != 0 && !in_array(ob.selectedIndex, indexes)) { 
      indexes.push(ob.selectedIndex) 
      arSelected.push(ob.options[ob.selectedIndex].value); 
     } 
     ob.options[ob.selectedIndex].selected = false; 
     i++; 
    } 
    var count = 0; 
    while(count < indexes.length){ 
     ob.options[indexes[count]].selected = true; 
     count ++; 
    } 
    return arSelected; 
} 

function in_array(needle, haystack) 
{ 
    for(var key in haystack) 
    { 
     if(needle === haystack[key]) 
     { 
      return true; 
     } 
    } 

    return false; 
}