How can I select children options from optgroup in Select2? - javascript

Question:
I have successfully created a select2 template with a group but I can't select the items in it, is there anything missing from the code I made below? Any help from you means a lot to me, thank you
See this first,
Preview Image
For the data below, i folow https://select2.org/data-sources/formats
Result from AJAX :
{
"status": true,
"message": null,
"data": [
{
"text": "Bank",
"children": [
{
"id": "002",
"icon": ".../payment/bri_1.png",
"text": "BANK BRI"
},
{
"id": "008",
"icon": ".../payment/mandiri_1.png",
"text": "BANK MANDIRI"
},
{
"id": "009",
"icon": ".../payment/bni_1.png",
"text": "BANK BNI / SYARIAH"
},
{
"id": "014",
"icon": ".../payment/bca_1.png",
"text": "BANK BCA"
},
{
"id": "022",
"icon": ".../payment/1280px-CIMB_Niaga_logo.svg.png",
"text": "CIMB NIAGA / SYARIAH"
},
{
"id": "016",
"icon": ".../payment/Maybank-Logo.png",
"text": "Maybank"
},
{
"id": "013",
"icon": ".../payment/images.png",
"text": "PERMATA BANK"
},
{
"id": "213",
"icon": ".../payment/Jenius-logo.png",
"text": "Jenius/BTPN"
},
{
"id": "011",
"icon": ".../payment/kissclipart-danamon-logo-png-clipart-bank-danamon-logo-a9b2b21755c37a3a.png",
"text": "Danamon"
},
{
"id": "012",
"icon": ".../payment/images_1.png",
"text": "Bank Neo Commerce/Bank Yudha Bakti"
},
{
"id": "017",
"icon": ".../payment/images-removebg-preview.png",
"text": "Bank Syariah Indonesia"
}
]
},
{
"text": "eMoney",
"children": [
{
"id": "900",
"icon": ".../payment/ovo.png",
"text": "OVO"
},
{
"id": "901",
"icon": ".../payment/gopay.png",
"text": "GOPAY"
},
{
"id": "903",
"icon": ".../payment/dana_1.png",
"text": "DANA"
},
{
"id": "904",
"icon": ".../payment/linkaja.png",
"text": "LINK AJA"
},
{
"id": "906",
"icon": ".../payment/shopeepay-shopee.co.id_ratio-16x9.jpg",
"text": "SHOPEE PAY"
}
]
}
]
}
Code :
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
minimumResultsForSearch: Infinity,
templateResult: function formatState(state) {
if (!state.id) return state.text;
var $state = $(
'<span><img src="' + state.icon + '" style="width:30px;"/> ' + state.text + '</span>'
);
return $state;
},
ajax: {
url: base_url + 'user/api/payment',
dataType: 'json',
processResults: function(data) {
return {
results: $.map(data.data, function(item, key) {
var children = [];
for (var k in item.children) {
var childItem = [];
childItem.id = item.children[k].id;
childItem.icon = item.children[k].icon;
childItem.text = item.children[k].text;
children.push(childItem);
}
return {
text: item.text,
children: children,
}
})
};
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Payment</label>
<div class="col-sm-10">
<select name="payment" id="payment" class="form-control">
</select>
</div>
</div>

As far as I can see in your code, your API is returning results already formatted, so keep it simple. Please check this fiddle with a fully working example based on your code.
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
ajax: {
url: 'https://randomuser.me/api/', //a random URL to simulate a request response in jsfiddle
dataType: 'json',
processResults: (data) => ({ results: response.data })
}
});

Related

Get all its parent nodes path for each child nodes

Hi I have below code running, but I would like to add one more property called path which should consist all its parent node path
Expected output I need something as I have shown for cardTtile, so I need same for each node.
[
{
"id": "cardShop",
"key": "cardShop",
"title": "cardShop",
"selectable": false,
"path":cardShop"
"children": [
{
"id": "cardData",
"key": "cardData",
"title": "cardData",
"parentId": "cardShop",
"path":cardShop.cardData"
"selectable": false,
"children": [
{
"id": "cardTitle",
"key": "cardTitle",
"title": "cardTitle",
"parentId": "cardData",
"path":cardShop.cardData.cardTitle"
"isLeaf": true
},
{
"id": "cardType",
"key": "cardType",
"title": "cardType",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "dtmProductName",
"key": "dtmProductName",
"title": "dtmProductName",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "viewAllCards",
"key": "viewAllCards",
"title": "viewAllCards",
"parentId": "cardData",
"selectable": false,
"children": [
{
"id": "url",
"key": "url",
"title": "url",
"parentId": "viewAllCards",
"isLeaf": true
},
{
"id": "text",
"key": "text",
"title": "text",
"parentId": "viewAllCards",
"isLeaf": true
}
]
}
]
},
{
"id": "eligibilityChecker",
"key": "eligibilityChecker",
"title": "eligibilityChecker",
"parentId": "cardShop",
"selectable": false,
"children": [
{
"id": "header",
"key": "header",
"title": "header",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "subHeader",
"key": "subHeader",
"title": "subHeader",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "bulletPoints",
"key": "bulletPoints",
"title": "bulletPoints",
"parentId": "eligibilityChecker",
"isLeaf": true
}
]
}
]
}
]
I have below running code example here. I tried to persist parentKey recursively but its not giving me expected output.
const transform = data => {
const loop = (data, parent) => Object.entries(data).map(([key, value]) => {
let additional = parent? {
parentId: parent
}:{}
if(typeof value === 'object' && !Array.isArray(value)){
additional = {
...additional,
selectable: false,
children: loop(value, key)
}
}else{
additional.isLeaf = true
}
return {
id: key,
key,
title: key,
...additional
}
})
return loop(data)
}
let jsonObj = {
"data": {
"cardShop": {
"cardData": {
"cardTitle": "The Platinum Card<sup>®</sup>",
"cardType": "credit-cards",
"dtmProductName": "PlatinumCard",
"viewAllCards": {
"url": "credit-cards/all-cards",
"text": "All Cards"
}
},
"eligibilityChecker": {
"header": "Check your eligibility",
"subHeader": "The Platinum Card®",
"bulletPoints": [
"Only takes a couple of minutes to complete",
"Will not impact your credit rating",
"Allows you to apply with confidence"
]
}
}
}
}
console.log(transform(jsonObj.data))
]
You suggestion would be appreciated
Thanks
You could take another variable for path and add the actual key to it.
const transform = data => {
const loop = (data, parentId, previousPath = '') => Object
.entries(data)
.map(([key, value]) => {
const
additional = parentId ? { parentId } : {},
path = previousPath + (previousPath && '.') + key;
Object.assign(
additional,
value && typeof value === 'object' && !Array.isArray(value)
? { selectable: false, children: loop(value, key, path) }
: { isLeaf: true }
);
return { id: key, key, title: key, path, ...additional };
});
return loop(data);
}
const data = { cardShop: { cardData: { cardTitle: "The Platinum Card<sup>®</sup>", cardType: "credit-cards", dtmProductName: "PlatinumCard", viewAllCards: { url: "credit-cards/all-cards", text: "All Cards" } }, eligibilityChecker: { header: "Check your eligibility", subHeader: "The Platinum Card®", bulletPoints: ["Only takes a couple of minutes to complete", "Will not impact your credit rating", "Allows you to apply with confidence"] } } };
console.log(transform(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

How To Get The Parent value from Json for this select2

var preload_data = [{
"id": 2049,
"text": "style",
"children": [{
"id": "6906957ed912c883",
"text": "Country"
}, {
"id": "d239d844608fdbcf",
"text": "Christmas"
}]
}, {
"id": 0,
"text": "unassigned",
"children": [{
"id": "52d8e1e8d419bb61",
"text": "Punk"
}, {
"id": "88b9826121aeb89b",
"text": "Upbeat"
}, {
"id": "8485e6dd8e33fc50",
"text": "test arda"
}, {
"id": "da9fa55495a4a463",
"text": "test1"
}, {
"id": "feb1177719f4b5a4",
"text": "test arda 3"
}, {
"id": "64a2ae4ec2c0a1ef",
"text": "Feel Good"
}, {
"id": "2512f7946f660dc5",
"text": "Happy"
}, {
"id": "b1e7203207bd068f",
"text": "Love"
}, {
"id": "fb3a42b8abbf975a",
"text": "Reminiscent"
}, {
"id": "56d60aed1278c5a0",
"text": "Indie"
}, {
"id": "5733de46970ac503",
"text": "Rock"
}, {
"id": "801c33b478d1d5be",
"text": "Singer Songwriter"
}, {
"id": "ee4c6f5c12782bb9",
"text": "World"
}, {
"id": "4605140218eb9e52",
"text": "Reality"
}, {
"id": "92934140c305706e",
"text": "Pop"
}, {
"id": "f40f55db44dc0846",
"text": "Acoustic"
}, {
"id": "07b3c4640e84bfeb",
"text": "Folk"
}]
}]
and I want the output for dropdown list
Style:Christmas for example
this is the select2 code
$("#hidStyles").select2({
containerCssClass: 'styleContainer',
data: preload_data,
width: '100%',
allowClear: true,
multiple: true,
dropdownCssClass: 'select2-hidden',
placeholder: 'Please enter the name of style here to assign it to this album',
formatSelection: format1,
escapeMarkup : function(m) { return m;},
formatSearching: null
//formatSelection : format
});
and this is How I format the Json :
function format1(item) {
opt = $("#hidStyles").find(':selected');
sel = opt.text;
//og = opt.closest(".select2-results-dept-0").attr(".select2-result-label");
ogx = opt.text.data.text;
return ogx + ':' + item.text;
}
how can I get the value so that it's like style : christmas
https://jsfiddle.net/jna7ft1c/3/
I am sorry the jsfiddle I am not familiar with for making the front end, but mostly the code is like written there

Get a value from Nested JSON

I am completely new to Node.js. I have to read specific value from a API responded Nested JSON. I have tried to figure out but getting Undefined instead of the value. Whenever I am trying to read the base object I am getting the responded value but whenever I am trying to read the object under array then I am getting Undefined value.
Code Snippet:
var https = require('https');
var optionget = {
host: 'api-dev.dataoverflow.com',
port: 443,
path: '/test1/test2/',
method: 'GET',
HEADERS: {
'Authorization': 'Basic grege==',
'X-PruAppID : '
PlainCardPortal '
}
};
console.info(optionsget)
var reqGet = htttps.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
process.stdout.write(jsonobj);
var Value = jsonobj.items.item.topping.type;
console.log(Value)
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
var optionsgetmsg = {
host: 'api-dev.dataoverflow.com',
port: 443,
method: 'GET'
};
console.info(optionsgetmsg);
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.setEncoding('utf-8')
res.on('data', function(data) {
process.stdout.write(data);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
Nested JSON Snippet:
{
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
...
]
}
}
I want to read type : Glazed from this JSON only but I am getting Undefined.
You have to iterate over the values in an array. You cannot access them using . notation. Use map to iterate over the array and get they types in the topping array
var jsonobj = {
"items": {
"item": [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
{
"id": "1003",
"type": "Blueberry"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
},
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
},
{
"id": "5006",
"type": "Chocolate with Sprinkles"
},
{
"id": "5003",
"type": "Chocolate"
},
{
"id": "5004",
"type": "Maple"
}
]
}
]
}
}
var Value = jsonobj.items.item.map(e=>e.topping)[0].map(x=>x.type);
console.log(...Value)

how to replace the value in an JSON array for a existing key?

In my application I have a ajax call and am getting the following response based on this am constructing the questions & answer section which I have included in the JSFiddle
var responseQuestions = {
"error": false,
"message": "Success",
"result": {
"Questions": [{
"Id": "131a",
"Text": "In what county do you live?",
"Answers": [{
"Id": "abc1",
"Text": "option1"
},
{
"Id": "abc2",
"Text": "option2"
},
{
"Id": "abc3",
"Text": "option3"
},
{
"Id": "abc4",
"Text": "option4"
},
{
"Id": "abc5",
"Text": "option5"
}
],
"SelectedAnswerId": null
},
{
"Id": "132a",
"Text": "Which zip code has ever been a part of your address?",
"Answers": [{
"Id": "def1",
"Text": "option1"
},
{
"Id": "def2",
"Text": "option2"
},
{
"Id": "def3",
"Text": "option3"
},
{
"Id": "def4",
"Text": "option4"
},
{
"Id": "def5",
"Text": "option5"
}
],
"SelectedAnswerId": null
},
{
"Id": "133a",
"Text": "What was the original amount of your most recent mortgage?",
"Answers": [{
"Id": "ghi1",
"Text": "option1"
},
{
"Id": "ghi2",
"Text": "option2"
},
{
"Id": "ghi3",
"Text": "option3"
},
{
"Id": "ghi4",
"Text": "option4"
},
{
"Id": "ghi5",
"Text": "option5"
}
],
"SelectedAnswerId": null
}
]
}
};
Required Format:
var responseQuestions = {
"error": false,
"message": "Success",
"result": {
"Questions": [{
"Id": "131a",
"Text": "In what county do you live?",
"Answers": [{
"Id": "abc1",
"Text": "option1"
},
{
"Id": "abc2",
"Text": "option2"
},
{
"Id": "abc3",
"Text": "option3"
},
{
"Id": "abc4",
"Text": "option4"
},
{
"Id": "abc5",
"Text": "option5"
}
],
**"SelectedAnswerId": "abc2"**
},
{
"Id": "132a",
"Text": "Which zip code has ever been a part of your address?",
"Answers": [{
"Id": "def1",
"Text": "option1"
},
{
"Id": "def2",
"Text": "option2"
},
{
"Id": "def3",
"Text": "option3"
},
{
"Id": "def4",
"Text": "option4"
},
{
"Id": "def5",
"Text": "option5"
}
],
**"SelectedAnswerId": "def1"**
},
{
"Id": "133a",
"Text": "What was the original amount of your most recent mortgage?",
"Answers": [{
"Id": "ghi1",
"Text": "option1"
},
{
"Id": "ghi2",
"Text": "option2"
},
{
"Id": "ghi3",
"Text": "option3"
},
{
"Id": "ghi4",
"Text": "option4"
},
{
"Id": "ghi5",
"Text": "option5"
}
],
**"SelectedAnswerId": "ghi2"**
}
]
}
};
Now I need to submit this answer with the same above mentioned format along the "SelectedAnswerId" value(in the above mentioned array "SelectedAnswerId" is null and now I have to include the original selected ans Id based on questions ).
I have tried to fetch all the selected ans id in a array and attached the same in jsfiddle but am unable to proceed on how to append this ans id in the existing array based on questions. How to achieve this ?
Try the following loops:
$('input[type="radio"]:checked').each(function() {
var questionId = $(this).closest('.radioGroup').prev().attr('id');//get the question id
var answerId = this.id;//get the answer id
$.each(responseQuestions.result.Questions, function(i, v) {//loop each question
if (v.Id == questionId) {
$.each(v.Answers, function(ind, val) {//loop each answer
if (val.Id == answerId) {
responseQuestions.result.Questions[i]['SelectedAnswerId'] = answerId;//save the answer
}
});
}
});
});
console.log(responseQuestions);
demo:https://jsfiddle.net/mj3gvd5e/1/
Note: you need to change your question id to remove or add the a to be consistent both in the page and in the json
You have to find index based on question id and then set answerid at specific index
var index = responseQuestions.result.Questions.findIndex(function(val){
return val.Id === yourQuestionid;
})
responseQuestions.result.Questions[index].SelectedAnswerId = youranswerID;
First of all you need to have your main question id and Ans id into same array as given fiddle by Madalin jsfiddle.net/6q9mct68
second you get this array, you can loop through your first array and replace the string by compairing Id,

Javascript multiple drop down box

Is there a way to get a multiple drop down field from a list of arrays without having to hardcode the information into the HTML? So that by selecting each category the relevant subcategory will drop down.
The list looks something like this:
var listData = [
{
"title": "Meeting Room",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Book a Car",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Stationery",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Hospitality",
"category": "Forms",
"url": "https://www.google.co.uk/"
},
{
"title": "Communications",
"category": "News",
"url": "https://blogs.office.com/"
},
{
"title": "Industries",
"category": "News",
"url": "https://blogs.office.com/"
},
{
"title": "Policy",
"category": "News",
"url": "https://blogs.office.com/"
},
{
"title": "Get started",
"category": "Information",
"url": "https://support.office.com/"
},
{
"title": "What do you need",
"category": "Useful Information",
"url": "https://support.office.com/"
},
{
"title": "Accessibility features",
"category": "Useful Information",
"url": "https://support.office.com/"
},
{
"title": "Videos",
"category": "Useful Information",
"url": "https://support.office.com/"
}
]
The following code does the work. It's vanilla JS.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Form</title>
</head>
<body>
<select id="categories" onchange="changeCategory(event)"> </select>
<select id="title"> </select>
<select id="url"> </select>
<script>
var listData = [{
"title": "Meeting Room"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Book a Car"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Stationery"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Hospitality"
, "category": "Forms"
, "url": "https://www.google.co.uk/"
}, {
"title": "Communications"
, "category": "News"
, "url": "https://blogs.office.com/"
}, {
"title": "Industries"
, "category": "News"
, "url": "https://blogs.office.com/"
}, {
"title": "Policy"
, "category": "News"
, "url": "https://blogs.office.com/"
}, {
"title": "Get started"
, "category": "Information"
, "url": "https://support.office.com/"
}, {
"title": "What do you need"
, "category": "Useful Information"
, "url": "https://support.office.com/"
}, {
"title": "Accessibility features"
, "category": "Useful Information"
, "url": "https://support.office.com/"
}, {
"title": "Videos"
, "category": "Useful Information"
, "url": "https://support.office.com/"
}];
function removeOptions(selectbox) {
var i;
for (i = selectbox.options.length - 1; i >= 0; i--) {
selectbox.remove(i);
}
}
function changeCategory(event) {
removeOptions(document.getElementById('title'))
removeOptions(document.getElementById('url'))
mySelect1 = document.getElementById('title')
mySelect2 = document.getElementById('url');
listData.forEach(function (item, index) {
if (item.category == event.target.value) {
mySelect1.options[mySelect1.options.length] = new Option(item.title, item.title);
mySelect2.options[mySelect2.options.length] = new Option(item.url, item.url);
}
});
}
Array.prototype.contains = function (obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
var mySelect = document.getElementById('categories');
var categories = new Array;
listData.forEach(function (item, index) {
if (!categories.contains(item.category)) {
mySelect.options[mySelect.options.length] = new Option(item.category, item.category);
categories.push(item.category);
}
});
</script>
</body>
</html>

Categories

Resources