Search code examples
jquery-select2-4

Select2 v4 append not working for multiple select controls


I have a table with select2 selections. Each row has an add button with a default value in the attribute. When the user adds an item each select2 box with the same default value has to be updated. Here is a part of my code:

<tr>
    <td>
        <div class="gb-select-div"  rowId="279525">
            <select class="idInLine">
                <option value="">--Select--</option>
            </select>
        </div>
    </td>
    <td>
        <a href='#' default="Piet" class='ui-icon ui-icon-circle-plus addId'></a>
    </td>
</tr>

var rowId;
var def;
var newOption = new Option(name, newId, true, true);
$(".idInLine").each(function() {
    rowId = $(this).closest('div').attr('rowId');
    def = $('#tr' + rowId).find(".addId").attr("default")
    if (def === defaultValue) {
        $(this).append(newOption).trigger('change');
    }
});

The code is almost working. A new item is added (Ajax). The select2 change event is triggered (selections are saved with Ajax). The only problem is; only one select2 control is showing the new value, the others keep showing "--Select--".

I am using the latest version of select2 v4.


Solution

  • Solved it. The line: var newOption = new Option(name, newId, true, true); had to be inside the each loop.