My solution is partially derived from the request logic. I post my solution here, hope this helps someone. Basically we make a request for a term, and if this term does not exist, we allow the user to click on a fake result (click here to add). In doing so, they trigger a request to add a term. After that, we clear the autocomplete with its initial status and add the newly created term in the div, which lists the selected terms. I also save the identifier, which will be saved after the user fills out the form.
$("#local-sponsor").autocomplete({ source: function (request, response) { $.ajax({ url: applications.Urls.FindLocalSponsor, dataType: "json", cache: false, data: { term: request.term, alreadyselected: function () { var ids = []; $("#localsponsor-div div.tagButton").each(function () { ids.push($(this).data("id")); }); return ids; } }, success: function (data) { if (data.length === 0) { data = [{ 'label': "Click here to create", "value": request.term, "id": -1 }]; } response(data); } }); }, minLength: 1, select: function (event, ui) { if (ui.item.id === -1) { $.ajax({ url: applications.Urls.AddLocalSponsor, type: 'POST', dataType: "json", cache: false, data: { term: ui.item.value }, success: function (data) { if (data.id !== 0) { var upto = parseInt($("#upto-localsponsor").val()); var e = '<div class="tagButton" data-id="' + data.id + '">' + data.value + '<a class="remove remove-researcher-co"></a><input type="hidden" name="LocalSponsors[' + upto + ']" id="LocalSponsors' + upto + '_" value="' + data.id + '"/></div>'; $("#localsponsor-div").append(e); $("#upto-localsponsor").val(upto + 1); } } }); $(this).val(''); return false; } else { var upto = parseInt($("#upto-localsponsor").val()); var e = '<div class="tagButton" data-id="' + ui.item.id + '">' + ui.item.label + '<a class="remove remove-researcher-co"></a><input type="hidden" name="LocalSponsors[' + upto + ']" id="LocalSponsors' + upto + '_" value="' + ui.item.id + '"/></div>'; $("#localsponsor-div").append(e); $("#upto-localsponsor").val(upto + 1); $(this).val(''); return false; } }, response: function(event, ui) { } }).data("ui-autocomplete")._renderItem = function (ul, item) { return $("<li></li>") .data("item.autocomplete", item) .append("<a>" + item.label + "</a>") .appendTo(ul); };
source share