Search code examples
jqueryformsjquery-select2jquery-select2-4

Select2 programatically append options not send in form


Why not recogonize the form when send the programatically append options to the Select2 element?

Html

Jquery Select2

$('#subrecursos').select2({
            width: null,
            multiple: true,
            allowClear: true,
            tags: true,
            "language": {
                "noResults": function () {
                    return "<i>Please Add Subresource as 'Name'|'Cost'|'Price'|'Capacity'(19V|50|70|2 or 20V)</i>";
                }
            },
            escapeMarkup: function (markup) {
                return markup;
            },
            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 };
                }
            }

        });

Jquery Append options

for (var i = 0; i < parseInt($("#limitsub").val()) ; i++)
  {            
    var valsub = (i + 1) + '-' + $("#nsubcant").val() + '|||' + $("#cantsub").val();
    var option='<option value="' + valsub + '" >' + valsub + '</option>'; 
    $("#subrecursos").append(option);//append the option
    $(".select2-selection__rendered").append('<li class="select2-selection__choice" title="' + valsub + '"><span class="select2-selection__choice__remove" role="presentation">×</span>' + valsub + '</li>');
    //append the tags
  }

Before Append: enter image description here

After Append: enter image description here

Until here everything is ok, But when send the form , the options are not recognize. When add the tags typing the options are recognize in the form. Why happend this? why only recognize the options typed and not programatically added? Thank you a lot!!


Solution

  • The way you append your options $(".select2-selection__rendered").append( is not good for select2 , when you send the form select2 need to format your selection for form data but your selection are no where to be found inside select2 data collection.

    $("#subrecursos").append(option); this way is good way but after you must $("#subrecursos").val([1,2]).trigger('change') to make the multiple selection

    Take a look at this answer, the person requested how to add select2 option and select them. I think it exactely what u need in a more robust way