jquery remove/add select options after cloning sel

2019-02-28 09:49发布

问题:

I need to be able to clone a drop down list and filter only those options that were NOT yet selected in the group of select lists.

For example, having the following:

<select name="SelectService" class="selService">
<option value="1">Some service</option>
<option value="2">Another one</option>
<option value="3">One more</option>
</select>

When i click the "clone" button it would clone the select list with ONLY those options that have NOT been yet selected.

ex: select option "Some service" -> hit clone -> new select list is added with only option values: 2 and 3.

etc..cloning and removing select lists would re-fill the select lists based on options selected so far.

EDIT: to better visualize it here is the screen shot:

SCENARIO:

  1. i start off with only 1 drop down list (that has 5 options) => 1,2,3,4,5 -> first options is selected by default.
  2. I hit clone -> new list is added with ONLY options 2,3,4,5.
  3. i select option 5 (in select list

    2)

  4. I hit clone -> new list (#3) is added with ONLY options 2,3,4
  5. i select option 2 (in select list

    3)

  6. I hit clone -> new list (#4) is created with options 3,4

..and so on.

Now, When I remove Select list #2 (or any other select list) that means ALL select lists should re-fresh and include the selected option from deleted select list (in our case #2)

Help. thanks

回答1:

This seems to do what you want: http://jsfiddle.net/infernalbadger/SKVSu/1/

$('#clone').click(function() {
    var original = $('select.selService:eq(0)');
    var allSelects = $('select.selService');
    var clone = original.clone();

    $('option', clone).filter(function(i) {
        return allSelects.find('option:selected[value="' + $(this).val() + '"]').length;
    }).remove();

    $('#target').append(clone).append('<br />');
});