简体   繁体   中英

Display Select2 value not in list

While a new value may be added to the Select2 (3.5) element using createSearchChoice, how can I get a new value to display if it is not in the list? I can add values not in the Select2 list, but how would a default value not in the list be displayed?

$("#select").select2({
    placeholder: "Who is the invoice from?",
    minimumInputLength: 2,
    quietMillis: 300,
    allowClear : true,
    ajax: {
        url: "accountsDataStore.xsp",
        dataType: 'json',
        data: function (term, page) {
            return {
                q: term, // search term
                page_limit: 10
            };
        },
        results: function (data, page) { return data; }
    },

    // extra code to allow entering value not in list
    id: function(object) { return object.text; },

    //Allow manually entered text in drop down.
    createSearchChoice:function(term, data) {
                        if ( $(data).filter( function() {
                                  return this.text.localeCompare(term)===0;
                              }).length===0) {
                                      return {id:term, text:term};
                        }
    },

    initSelection: function(element, callback) {
                        //sets a default value (if a value was selected previously)
                        //get the existing value
                        var id = $(element).val();

                        //if a value was selected: perform an Ajax call to retrieve the text label      
                        if (id !== "") {
                            $.ajax( 
                                "accountsDataStore.xsp", {
                                    data: { id: id },
                                    dataType: "json"
                                }).done(function(data) { 
                                       // ** TODO if value not found, display current element value -- HOW??  **
                                       callback(data); });
                        }
                    }

    }).on('change', function (evt) {
                              // Do something after value changes
                              }
);

During initSelection , if the default value is not found, then how to display the current value?

<input type="hidden" 
       id="view:_id1:_id4:callback1:inputName" 
       name="view:_id1:_id4:callback1:inputName" 
       aria-required="true" 
       value="ACME Company" 
       tabindex="-1" 
       class="select2-offscreen">

In the form, the value is set, it just does not display in the <span> where a selected value appears. Do we just add it to the list somehow?

Thanks.

I personally handle select2 elements that allow values not in list as follows through the proper use of a view controller (viewScoped bean).

With the following code I do 3 things:

<xp:comboBox id="comboDemo" value="#{ctrl.comboValue}" validator="#{ctrl.validateCombo}">
   <xp:selectItems value="#{ctrl.comboChoices}" />
 </xp:comboBox>
  1. I bind the value for the combo
  2. I make sure that any new option that was created and selected client-side gets accepted
  3. I load default choices for the combobox

Default choices are built keeping into account the current bound value, unless it's null .

public List<SelectItem> getComboChoices() {
    if (comboChoices == null) {
        comboChoices = new ArrayList<SelectItem>();

        // Complete with your own logic here
        if (StringUtil.isNotEmpty(comboValue)) {
            comboChoices.add(new SelectItem(comboValue, comboValue));
        }
    }

    return comboChoices;
}

Once a new value is chosen I need to make sure it will be accepted in its way back to the server. I exploit the validation phase to sneak in the new value.

public void validateCombo(FacesContext facesContext, UIComponent component, Object value) {
    boolean isNewValue = true;

    for (SelectItem item : comboChoices) {
        if (value.equals(item.getValue())) {
            isNewValue = false;
            break;
        }
    }

    if (isNewValue) {
        String newValue = (String) value;
        comboChoices.add(new SelectItem(newValue, newValue));
    }
}

The above is a dumbed down version of what I do. You can make it smarter than that but I hope the example was clear enough.

Dynamic option creation

In addition to a prepopulated menu of options, Select2 can dynamically create new options from text input by the user in the search box. This feature is called "tagging". To enable tagging, set the tags option to true:

look here for detailed info

in select2 what you intend to do is called tagging and here is how it goes;

<select class="form-control">
  <option selected="selected">orange</option>
  <option>white</option>
  <option>purple</option>
</select>

//the major ish
$(".js-example-tags").select2({
  tags: true
});

in plain english just set tags during initialization of select2 and you have the option to add a value that is not in the dropdown.

hope this was helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM