Jquery adding and removing items from listbox

后端 未结 9 938
粉色の甜心
粉色の甜心 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:40

    Get existing list of options, check if those you're adding already exist, if not, add them:

    http://jsfiddle.net/bZXs4/

    $('#add').click(function () {
         var inHTML = "";
         var $opts = $('#SelectedItems').find('option'); 
    
         $("#SelectBox2 option:selected").each(function () {
             var allowItemToBeAdded = true;
             var selectedVal = $(this).val();
             $opts.each(function(index, element){
                 if($(this).val() === selectedVal){
                     allowItemToBeAdded = false;
                 }
             });
    
             if(allowItemToBeAdded){
                 inHTML += '<option value="' + selectedVal + '">' + $(this).text() + '</option>';
             }
         });
    
         if(inHTML !== ''){
             $("#SelectedItems").append(inHTML);
         }
     });
    
    0 讨论(0)
  • 2021-02-03 13:41

    SEE THE LINK

    write if condition as

     if($("#SelectedItems option:contains("+$(this).val()+")").length<=0)                
       inHTML += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
    

    Then add

    $('#remove').click(function(){
    
      $('#SelectedItems  :selected').each(function(i, selected) {
        $(this).remove();
    });
    });
    
    0 讨论(0)
  • 2021-02-03 13:45

    Have a look at this solution:- Using the data attribute to keep track of the items parent list selector and avoiding a loop with the help of this selector and data attribute.

    http://jsfiddle.net/pramodsankar007/rMpBv/

     $('#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').clone(true));
               }
            });
            $("#SelectedItems").append(itemsToAdd);
        });
    });
    
    0 讨论(0)
提交回复
热议问题