'Set title of preselected values of Select2
I attached preselected values of Select2 using AJAX like below.
$.ajax({
type: 'POST',
dataType: 'json',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
// url: "/wp-admin/admin-ajax.php",
data: {
element_id: element_id,
action: 'get_preselect_values',
},
}).then(function (data) {
var options = [];
if (data) {
$.each(data, function (index,text) {
options.push(new Option(text['text'], text['id'], true, true));
});
}
selectEle.append(options).trigger('change');
}
I would like to set title of preselected values.
I tried with below code.
$.ajax({
type: 'POST',
dataType: 'json',
url: "/wp-admin/admin-ajax.php",
data: {
element_id: element_id,
action: 'get_preselect_values',
},
}).then(function (data) {
var options = [];
if (data) {
$.each(data, function (index,text) {
var user_data = '<table> \
<tr> \
<td>Organisation</td> \
<td>'+text[0][1]+'</td> \
</tr> \
<tr> \
<td>Age</td> \
<td>'+ text[0][0]+'</td> \
</tr> \
</table>';
var opt = new Option(text['text'], text['id'], true, true);
opt.attr("title",user_data);
options.push(opt);
});
}
selectEle.trigger('change');
Solution 1:[1]
Try method of select2 when an item is selected
$('#example').on('select2:select', function (e) {
$(this).attr('title', 'some value title');
});
Solution 2:[2]
I think you are looking for templateSelection option.
$(".js-example-templating").select2({
templateSelection: formatState,
});
function formatState(state) {
return $(
`<span class='tooltip' title='${state.title}'>${state.text}</span>`
);
}
Edit: add selectEle.append(opt); before triggering change
$.ajax({
type: "POST",
dataType: "json",
url: "/wp-admin/admin-ajax.php",
data: {
element_id: element_id,
action: "get_preselect_values",
},
}).then(function (data) {
// var options = [];
if (data) {
$.each(data, function (index, text) {
var user_data =
"<table> \
<tr> \
<td>Organisation</td> \
<td>" +
text[0][1] +
"</td> \
</tr> \
<tr> \
<td>Age</td> \
<td>" +
text[0][0] +
"</td> \
</tr> \
</table>";
var opt = new Option(text["text"], text["id"], true, true);
opt.attr("title", user_data);
// options.push(opt);
selectEle.append(opt); // added codes
});
selectEle.trigger("change");
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BoBiTza |
| Solution 2 |

