需要帮助从selectbox添加选定的项目到div(动态添加)



我需要在下面的div中显示所选择的子类别(多个),并且在某些情况下,我需要关闭从选择框中选择错误的div元素,以便我可以添加和删除元素到div(通过上面的selectbox)。

即使我做了类似的代码,但它不工作的多选择

简单地说,我需要选择的类别(多)与关闭按钮在下面的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>

遍历option,检查它们是否被选中,如下所示:

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>";
        }
    }
}

下面是一些适合您的方法: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;
}

最新更新