Jquery adding and removing items from listbox

后端 未结 9 946
粉色の甜心
粉色の甜心 2021-02-03 13:13

I\'ve created this fiddle, it allows the user to click on either art or video, dynamically populating the the second listbox with the list associated with those selections. Ther

9条回答
  •  名媛妹妹
    2021-02-03 13:33

    If you want to dynamically add and delete rows seamlessly try this way

    http://jsfiddle.net/WX4Nw/

    Adding a pointer to the selecteditems list as a data attrib to the root item key will help you control so that you can easily manage add/remove.

    Snippet from fiddle:-

    $('#SelectBox').change(function () {
            var str = "",
                inHTML = "",
                key = $('#SelectBox').val(),
                items;
            items = $(this).val() == 'art' ? artItems : vidItems;
            $.each(items, function (i, ob) {
                if($('#SelectedItems option[value="' + i + '"][data-key="' + key + '"]').length == 0)
                    inHTML += '';
            });
            $("#SelectBox2").empty().append(inHTML);
        });
    
     $('#add').click(function () {
            var itemsToAdd = [];
            $("#SelectBox2 option:selected").each(function () {
                var optionVal = $(this).val();
                var key = $(this).data('key');
                if ($('#SelectedItems option[value="' + optionVal + '"][data-key="' + key + '"]').length == 0)                     {
                    itemsToAdd.push($(this).removeAttr('selected'));
                }
            });
            $("#SelectedItems").append(itemsToAdd);
        });
    

提交回复
热议问题