In jQuery UI autocomplete, I just want to add my custom attribute. But, I tried below code. It's not working for me. It was replace whole <li>
html content.
What I tried :
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>").attr( "data-id",item.value).append(item.label).appendTo(ul);
};
Output of above code :
<ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all" id="ui-id-1" tabindex="0" style="display: none; width: 562px; top: 592px; left: 767px;">
<li data-id="220">Que 1</li>
<li data-id="219">Que 2</li>
<li data-id="218">Que 3</li>
<li data-id="217">Que 4</li>
</ul>
Rendered HTML (By Default Code of jQuery UI Autocomplete):
<ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all" id="ui-id-1" tabindex="0" style="display: none; width: 562px; top: 593px; left: 767px;">
<li class="ui-menu-item" role="presentation"><a id="ui-id-2" class="ui-corner-all" tabindex="-1">Que 1</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-3" class="ui-corner-all" tabindex="-1">Que 2</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-4" class="ui-corner-all" tabindex="-1">Que 3</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-5" class="ui-corner-all" tabindex="-1">Que 4</a></li>
</ul>
Expected Output :
<ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all" id="ui-id-1" tabindex="0" style="display: none; width: 562px; top: 593px; left: 767px;">
<li class="ui-menu-item" role="presentation"><a id="ui-id-2" class="ui-corner-all" tabindex="-1" data-id="220">Que 1</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-3" class="ui-corner-all" tabindex="-1" data-id="221">Que 2</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-4" class="ui-corner-all" tabindex="-1" data-id="222">Que 3</a></li>
<li class="ui-menu-item" role="presentation"><a id="ui-id-5" class="ui-corner-all" tabindex="-1" data-id="223">Que 4</a></li>
</ul>
If you want to keep everything the same as the original output and then add the data-id
you have to build the whole <li>
again, since you're overriding the default render function.
So you would do:
.data("ui-autocomplete")._renderItem = function (ul, item) {
const htmlstring = `<li class="ui-menu-item" role="presentation"><a class="ui-corner-all" tabindex="-1"></a></li>`;
const $li = $(htmlstring);
const id = $(ul).find('li').length + 1;
$li.find('a').attr("data-id", item.value).attr("id", id).html(item.label);
return $li.appendTo(ul);
};