Select2: Unable to update value of tags based dropdown

298 Views Asked by At

I am unable to dynamically populate Select2 drop-down with a custom value using the tags option.

It works only if I set one of the existing values. So one possible solution could be to dynamically add the option to select & then set the new value.

The HTML

<select id="list" name="nombres" style="width:50%"></select>
<br>
<button id="existing">Existing</button>
<button id="custom">Custom</button>

The javascript

$(document).ready(function() {
    $("#list").select2({
        placeholder: "Click 'Update'",
        allowClear: true,
        tags: true,
        data:[ 
            "AAA", "BBB", "CCC"
        ]
        });
    $("#existing").on('click', function() {
        $("#list").val("CCC").trigger("change");
    });
    $("#custom").on('click', function() {
        $("#list").val("ZZZ").trigger("change");
    });
});

Fiddle: https://jsfiddle.net/mmh2y85h/

UPDATE - Added solution with above mentioned approach (Adding option dynamically & then selecting the value)

$("#custom").on('click', function() {
        var newVal = '555';
        if ($("#list").find("option[value='" + newVal + "']").length<=0) {
          $("#list").append(new Option(newVal, newVal));
        } 
        $("#list").val(newVal).trigger("change");
});

Fiddle: https://jsfiddle.net/8zqegLqm/1/

1

There are 1 best solutions below

1
On

I changed

$("#list").val("ZZZ").trigger("change"); 

to

$("#list").append("<option>ZZZ</option>");

and it started working for me https://jsfiddle.net/bindrid/mmh2y85h/1/