Hi,
I’m working on a project. I want to use select2 with json data source. I have a problem with my json structure.
My CODE:HTML:
<select class="form-control form-control-lg" id="pt" name="SNA" required> </select>
jQuery:
function formatPT (pt) {
if (!pt.id) {
return pt.text;
}
//sername
$("#ptsername").val(pt.text);
if (pt.ic === 1){
var $container = $(
"<div class='select2-result-pedra clearfix'>" +
"<div class='select2-result-pedra-pt text-success'></div>" +
"</div>"
);
$container.find(".select2-result-pedra-pt").text(pt.text);
return $container;
} else {
var $container = $(
"<div class='select2-result-pedra clearfix'>" +
"<div class='select2-result-pedra-pt text-danger'></div>" +
"</div>"
);
$container.find(".select2-result-pedra-pt").text(pt.text);
return $container;
}
};
$("#pt").select2({
placeholder: 'Select a Service',
language: "fa",
multiple: false,
allowClear: true,
dropdownAutoWidth: false,
dir: "rtl",
templateSelection: formatPT,
minimumInputLength: 2,
language: {
searching: function () {
return "Searching...";
},
inputTooShort: function () {
return "enter at least 2 characters to start...";
}
},
ajax: {
url: '/ssoservices.php',
dataType: 'json',
type: "POST",
delay: 250,
data: function (params) {
return {
search: params.term,
ServiceType: 13
};
},
processResults: function(res) {
return {
results: $.map(res.data.list, function(item) {
return {
text: item.srvName,
id: item.srvId,
ic: item.srvBimSw
}
}),
};
},
cache: false
}
});
My Json structure: (ssoservices.php):
{
"status": 200,
"family": "SUCCESSFUL",
"reason": "OK",
"data": {
"list": [
{
"srvId": 61415,
"srvType": {
"srvType": "17",
"srvTypeDes": "Misc.",
"status": "1",
"statusstDate": "13940101",
"custType": "1"
},
"srvCode": "830004",
"srvName": "Service ONE",
"srvBimSw": "1",
"srvSex": null,
"srvPrice": 0,
"srvPriceDate": "13990101",
"doseCode": null,
"formCode": null,
"parTarefGrp": null,
"status": "1",
"statusstDate": "13990101",
"bGType": null,
"gSrvCode": null,
"agreementFlag": null,
"isDeleted": "0",
"visible": "1",
"dentalServiceType": "2",
"wsSrvCode": "0000830004"
},
{
"srvId": 61414,
"srvType": {
"srvType": "17",
"srvTypeDes": "Misc.",
"status": "1",
"statusstDate": "13940101",
"custType": "1"
},
"srvCode": "830003",
"srvName": "Service TWO",
"srvBimSw": null,
"srvSex": null,
"srvPrice": 248500,
"srvPriceDate": "13990201",
"doseCode": null,
"formCode": null,
"parTarefGrp": null,
"status": "1",
"statusstDate": "13990201",
"bGType": null,
"gSrvCode": null,
"agreementFlag": null,
"isDeleted": "0",
"visible": "1",
"dentalServiceType": "2",
"wsSrvCode": "0000830003"
}
],
"total": 2
}
}
MY PROBLEM:
I want to set the “srvId” as the id of select option?! I can’t set it? What’s wrong with my code?Thanks