2011-08-15 98 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; 
}