You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery Chosen动态AJAX调用选项重复及默认值丢失问题求助

How to Clear Chosen Dropdown While Preserving Selected Values

Got it, let's work through this problem together. The core issue here is balancing dynamic option loading with keeping your selected values intact and avoiding duplicate <option> elements. Here's how to fix your code effectively:

Key Fixes Breakdown

  1. Save selected values first: Capture the current selected options before making any changes to the dropdown—this lets us restore them later.
  2. Prevent duplicate entries: Maintain a deduplicated list of all fetched items, and exclude already-selected items from new API responses when appending.
  3. Restore selected state explicitly: After rebuilding the dropdown, set the selected values back and trigger Chosen's update to sync the UI.

Modified Working Code

Here's the updated version of your script with the fixes applied:

$(this.el).ready(function(){ 
  setTimeout(function(){ 
    var subItemsData = []; 
    $(self.el).chosen({ 
      width: '100%', 
      allow_single_deselect: true, 
      no_results_text: "Oops, nothing found!", 
      search_contains: false, 
      max_selected_options: self.params.maxselected ? self.params.maxselected : 0 
    }).on('change', function(evt, params) { 
      var value = $(self.el).val(); 
      self.set(value); 
      console.log("value",value); 
    }).on('chosen:showing_dropdown', function(evt, params) { }) 

    $('#patient_diagnosis_chosen ul li.search-field input').autocomplete({ 
      source: function( request, response ) { 
        if(request.term.length >= self.params.minlength){ 
          $.ajax({ 
            url: baseURL+'api/service/v1/get-data', 
            dataType: "json", 
            method:'post', 
            data:{ 
              'ids':$(self.el).val(), 
              'key':request.term 
            }, 
            success: function( data ) { 
              // 1. Save currently selected values (handle empty case with default array)
              const selectedValues = $(self.el).val() || [];

              // 2. Update master item list without duplicates
              data.input_data.forEach(item => {
                if (!subItemsData.some(existing => existing.id === item.id)) {
                  subItemsData.push(item);
                }
              });

              // 3. Clear the dropdown entirely
              $(self.el).empty();

              // 4. Re-add selected items (marked as selected to keep them in the dropdown)
              const selectedItems = subItemsData.filter(item => 
                selectedValues.includes(item.id.toString())
              );
              selectedItems.forEach(item => {
                $(self.el).append(`<option value="${item.id}" selected>${item.code} - ${item.short_description}</option>`);
              });

              // 5. Add new non-selected items from the API response
              const newItems = data.input_data.filter(item => 
                !selectedValues.includes(item.id.toString())
              );
              const subItems = newItems.map(item => 
                `<option value="${item.id}">${item.code} - ${item.short_description}</option>`
              );
              $(self.el).append(subItems);

              // 6. Restore selected values and refresh Chosen to sync UI
              $(self.el).val(selectedValues).trigger("chosen:updated");
            } 
          }); 
        } 
      } 
    }); 
  },100); 
});

Why This Solves Your Problems

  • No more duplicate options: We check if an item already exists in subItemsData before adding it, and we skip appending items that are already selected.
  • Selected values stay intact: We save the selected IDs before clearing the dropdown, re-add those items with the selected attribute, and explicitly set the dropdown's value back to the selected IDs before updating Chosen.
  • Chosen stays in sync: The chosen:updated trigger ensures the plugin reflects the new dropdown state correctly, so the UI matches the underlying select element.

Quick Optimization

If your API already excludes selected items from the response (thanks to the ids parameter you're sending), you can simplify the code by removing the newItems filter—just append all items from data.input_data directly after re-adding the selected ones.

内容的提问来源于stack exchange,提问作者Mdr Kuchhadiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:43:12