Export HTML data to excel - javascript

On my UI where I have A HTML table and some Input fields, all the fields have some data including table so what I am trying to do is :-
I want to export HTML full page data into excel,all input fields as well as table data, earlier I was using table2excel plugin but it is only exporting the HTML table data not input fields data
Code
var tableValue = [{
"Name": "vivek",
"Class": "12",
"English": 89,
"Maths": 45,
"Physics": 63
},
{
"Name": "Raul",
"Class": "11",
"English": 55,
"Maths": 45,
"Physics": 23
},
{
"Name": "Sam",
"Class": "12",
"English": 55,
"Maths": 68,
"Physics": 56
},
{
"Name": "Arun",
"Class": "12",
"English": 45,
"Maths": 78,
"Physics": 58
},
{
"Name": "Patric",
"Class": "12",
"English": 86,
"Maths": 45,
"Physics": 62
},
]
function addTable(tableValue) {
var $tbl = $("<table />", {
"class": "table table-striped table-bordered table-hover"
}),
$thd = $("<thead/>"),
$tb = $("<tbody/>"),
$trh = $("<tr/>", {
"class": "text-center"
});
$.each(Object.keys(tableValue[0]), function(_, val) {
$("<th/>").html(val).appendTo($trh);
});
$trh.appendTo($thd);
$.each(tableValue, function(_, item) {
$tr = $("<tr/>");
$.each(item, function(key, value) {
if (typeof(value) === 'number') {
$("<td/>", {
"class": "text-right"
}).html(value).appendTo($tr);
} else {
$("<td/>", {
"class": "text-left"
}).html(value).appendTo($tr);
}
$tr.appendTo($tb);
});
});
$tbl.append($thd).append($tb);
$("#grnReportTable").html($tbl);
}
$("#supplierAddReport").val("STILL FLOOR, NO. 34, 2ND CROSS, SWASTHI ROAD, SHANTINAGAR, BANGALORE, 560027 Contact Name: SURESH, Contact No. 22745206 GST No. : 29210085111, Email Id: ALPINEPRODUCTS#GMAIL.COM")
addTable(tableValue)
$("#export").click(function() {
$("#grnReportTable").table2excel({
filename: "Data"
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<script src="https://cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script>
<div class="container">
<div class="container" id="grnReportTable"></div>
<div class="form-row">
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-3">
<label for="mrk1">Marks 1</label>
<div class="input-group">
<input type="tel" class="form-control" aria-label="Text input with dropdown button" name="mrk1" id="mrk1" readonly="readonly" tabindex="-1" value="50">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-3">
<label for="mrk2">Marks 2</label>
<div class="input-group">
<input type="tel" class="form-control" aria-label="Text input with dropdown button" name="mrk2" id="mrk2" readonly="readonly" tabindex="-1" value="50.22">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-3">
<label for="mrk3">Marks3</label>
<div class="input-group">
<input type="tel" class="form-control" aria-label="Text input with dropdown button" name="mrk3" id="mrk3" readonly="readonly" tabindex="-1" value="43">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-8">
<label for="supplierAddReport">Suppl. Address</label>
<div class="input-group">
<textarea class="form-control" rows="3" readonly="readonly" name="supplierAddReport" id="supplierAddReport"></textarea>
</div>
</div>
</div>
</div>
<button id="export" class="btn btn-default commonButton">
<i class='fas fa-file-export'></i> Export
</button>
<script
src="https://cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script>
The table to excel plugin only export HTML table but I want to export Full page Data here i am only showing input fields but in my actual code I have some text areas as well as select option
i want to export it like

Instead of convert html to excel, change your scenario to convert JSON to CSV. Because, you have data and your data is JSON, that can convert to html table or CSV or other types, and solution of JSON to CSV is better than html to excel.
First: Prepare data.That means convert your data to your schema, you wanted export.
var tableValue = [
{ // Row for Marks 1
"Name": "Marks 1",
"Class": "50",
"English": "",
"Maths": "",
"Physics": ""
},
{ // Row for Marks 2
"Name": "Marks 2",
"Class": "55.22",
"English": "",
"Maths": "",
"Physics": ""
},
{ // Row for Marks 3
"Name": "Marks 3",
"Class": "43",
"English": "",
"Maths": "",
"Physics": ""
},
{
"Name": "",
"Class": "",
"English": "",
"Maths": "",
"Physics": ""
},
{
"Name": "Name",
"Class": "Class",
"English": "English",
"Maths": "Maths",
"Physics": "Physics"
},
{
"Name": "vivek",
"Class": "12",
"English": 89,
"Maths": 45,
"Physics": 63
},
{
"Name": "Raul",
"Class": "11",
"English": 55,
"Maths": 45,
"Physics": 23
},
{
"Name": "Sam",
"Class": "12",
"English": 55,
"Maths": 68,
"Physics": 56
},
{
"Name": "Arun",
"Class": "12",
"English": 45,
"Maths": 78,
"Physics": 58
},
{
"Name": "Patric",
"Class": "12",
"English": 86,
"Maths": 45,
"Physics": 62
}
]
, now You do not need any additional library, use this code :
// JAVASCRIPT
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = this.convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
function download(){
var headers = {
Name: '', // remove commas to avoid errors
Class: '',
English: '',
Maths: '',
Physics: ''
};
itemsNotFormatted = [
{
"Name": "Marks 1",
"Class": "50",
"English": "",
"Maths": "",
"Physics": ""
},
{
"Name": "Marks 2",
"Class": "55.22",
"English": "",
"Maths": "",
"Physics": ""
},
{
"Name": "Marks 3",
"Class": "43",
"English": "",
"Maths": "",
"Physics": ""
},
{
"Name": "",
"Class": "",
"English": "",
"Maths": "",
"Physics": ""
},
{
"Name": "Name",
"Class": "Class",
"English": "English",
"Maths": "Maths",
"Physics": "Physics"
},
{
"Name": "vivek",
"Class": "12",
"English": 89,
"Maths": 45,
"Physics": 63
},
{
"Name": "Raul",
"Class": "11",
"English": 55,
"Maths": 45,
"Physics": 23
},
{
"Name": "Sam",
"Class": "12",
"English": 55,
"Maths": 68,
"Physics": 56
},
{
"Name": "Arun",
"Class": "12",
"English": 45,
"Maths": 78,
"Physics": 58
},
{
"Name": "Patric",
"Class": "12",
"English": 86,
"Maths": 45,
"Physics": 62
}
];
var itemsFormatted = [];
// format the data
itemsNotFormatted.forEach((item) => {
itemsFormatted.push({
Name: item.Name, // remove commas to avoid errors,
Class: item.Class,
English: item.English,
Maths: item.Maths,
Physics: item.Physics
});
});
var fileTitle = 'SCORES'; // or 'my-unique-title'
exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download
}
// HTML CODE
<div class="download-wrapper" onClick="download()">
<p><i class="material-icons">file_download</i></p>
<p>Download Demo CSV File</p>
</div>
<p class="codepen" data-height="265" data-theme-id="0" data-default-tab="js,result" data-user="danny_pule" data-slug-hash="WRgqNx" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="JSON to CSV">
<span>See the Pen <a href="https://codepen.io/danny_pule/pen/WRgqNx/">
JSON to CSV</a> by Danny Pule (#danny_pule)
on CodePen.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
// RESULT

Related

How can I select children options from optgroup in Select2?

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 })
}
});

How to call specific Json Objects while search in all data accordingly using js?

Can anyone help me implement this JS code with my JSON file? I was looking through this javascript code to implement on my parsed JSON code but all the time it was confusing and irritating task to call specific EnrollmentNumber from search, validating it and then displaying the Enrollment Number Name of Person Marks.Name and Marks.External on the table as mentioned in js file.
I tried defining var but again and again, the code does not execute properly
var allData = []
var singleResult = {}
var activationList = {}
var regNo;
$('#registration-number').keypress("keypress", function(e) {
if (e.which == 13) {
calculate();
}
})
$("#calculate-button").click(function(){
calculate();
});
var calculate = () => {
regNo = $("#registration-number").val();
if(regNo != "non"){
getResult(regNo)
.then(() => {
return updateTable(regNo);
})
.then(() => {
return calculateGpa(regNo);
})
// here add ageregate also
.then((gpa) => {
$("#show-gpa").html('GPA : ' + gpa);
})
.catch((err) => {
alert('Registration number not found');
})
}else{
alert('Please fill the form')
}
}
// Fetch result from json file
var getResult = (regNo) => {
return new Promise((resolve, reject) => {
// Show loader
$('.loader').css('display', 'flex');
$.getJSON('results/33.json')
.then((res) => {
allData = res;
singleResult = allData.EnrollmentNumber[regNo];
createActivationList();
return resolve();
})
.catch((err) => {
return reject(err);
})
.then(() => {
// Remove loader
$('.loader').css('display', 'none');
})
});
}
// Initialize all subject activations to true
var createActivationList = () => {
activationList = {};
var result = singleResult;
var subs = Object.keys(result);
for(var i=0;i<subs.length;i++){
activationList[subs[i]] = true;
}
}
// Update result table
var updateTable = (regNo) => {
return new Promise((resolve, reject) => {
markup = '';
if(!singleResult)
return reject('Registration number not found');
subs = Object.keys(singleResult);
createMarkup(markup, singleResult, subs, 0)
.then((markup) => {
// Clear table
$('#subject-table tbody').html('');
// Update table
$('#subject-table tbody').append(markup);
// Show table
$('#result').show();
return resolve();
})
.catch((err) => {
return reject(err);
});
});
}
// Create markup of rows
var createMarkup = (markup, result, subs, counter) => {
return new Promise((resolve, reject) => {
if(counter < subs.length){
var subjectId = subs[counter];
var subjectGrade = result[subs[counter]];
var subjectName = allData['Marks'][subs[counter]]['Name'];
markup += `<tr>
<td>
<label class="checkbox-container">
<input type="checkbox" checked="true" id="${subjectId}" onchange="toggleActivation('${subjectId}')">
<span class="checkmark"></span>
</label>
</td>
<td>
<div class="subject-title">${subjectName}</div>
</td>
<td>
<div class="subject-grade">${subjectGrade}</div>
</td>
</tr>`;
return resolve(createMarkup(markup, result, subs, counter+1))
}else{
return resolve(markup);
}
});
}
// Calculate GPA
var calculateGpa = (regNo) => {
return new Promise((resolve, reject) => {
var result = singleResult;
var subs = Object.keys(result);
var totalCredit = 0.0;
var pointSum = 0.0;
for(var i=0; i<subs.length; i++){
if(activationList[subs[i]]){
var subjectGrade = result[subs[i]];
var subjectCredit = allData['Marks'][subs[i]]['Credits'];
pointSum += (gradeToPoint(subjectGrade) * subjectCredit);
totalCredit += subjectCredit;
}
}
var gpa = pointSum / totalCredit
gpa = Math.round((gpa) * 100) / 100
return resolve(gpa);
});
}
// Convert grade to point
var gradeToPoint = (grade) => {
if(grade >= '90')
return 10;
else if(grade >= '75')
return 9;
else if(grade >= '65')
return 8;
else if(grade >= '55')
return 7;
else if(grade >= '50')
return 6;
else if(grade >= '45')
return 5;
else if(grade >= '40')
return 4;
else
return 0;
}
var goBack = () => {
window.history.back();
}
This is my JSON file format
{
"Semester": "07",
"Programme": "BACHELOR OF TECHNOLOGY (ELECTRICAL & ELECTRONICS ENGINEERING)",
"Batch": "2015",
"Examination": "REGULAR December, 2018",
"Institution": "BHARATI VIDYAPEETH COLLEGE OF ENGINEERING",
"CollegeCode": "115",
"EnrollmentNumber": "00211504915",
"Name": "ABHISHEK",
"Marks": [
{
"Id": "49401",
"Credits": "4",
"Internal": "16",
"External": "67",
"Total": 83,
"Grade": "A+",
"Name": "ELECTRICAL DRIVES"
},
{
"Id": "49403",
"Credits": "4",
"Internal": "18",
"External": "60",
"Total": 78,
"Grade": "A+",
"Name": "ADVANCED CONTROL SYSTEMS"
},
{
"Id": "49405",
"Credits": "3",
"Internal": "18",
"External": "56",
"Total": 74,
"Grade": "A",
"Name": "EHV AC AND HVDC TRANSMISSIONS"
}
],
"CreditsSecured": "25",
"_id": "5cd3d6ae390a7a20c80b75f7"
},
{
"Semester": "07",
"Programme": "BACHELOR OF TECHNOLOGY (ELECTRICAL & ELECTRONICS ENGINEERING)",
"Batch": "2015",
"Examination": "REGULAR December, 2018",
"Institution": "BHARATI VIDYAPEETH COLLEGE OF ENGINEERING",
"CollegeCode": "115",
"EnrollmentNumber": "00411504915",
"Name": "AKHIL KHANDELWAL",
"Marks": [
{
"Id": "49401",
"Credits": "4",
"Internal": "19",
"External": "59",
"Total": 78,
"Grade": "A+",
"Name": "ELECTRICAL DRIVES"
},
{
"Id": "49403",
"Credits": "4",
"Internal": "18",
"External": "56",
"Total": 74,
"Grade": "A",
"Name": "ADVANCED CONTROL SYSTEMS"
}
],
"CreditsSecured": "25",
"_id": "5cd3d6ae390a7a20c80b75f8"
}
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="GPA">
<meta name="keywords" content="calculator">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0">
<meta name="theme-color" content="#3F6AE6">
<title>GPA Calculator</title>
<link rel="icon" sizes="512x512" href="img/calculator.png">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link href="css/mont.css" rel="stylesheet">
<link rel="manifest" href="manifest.json">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/viewer.css" rel="stylesheet">
</head>
<body>
<!-- LOADER -->
<div class="loader"><img src="img/loader.gif" class="img-loader"></div>
<!-- SIDEBAR BUTTON -->
<span onclick="goBack()" class="sidebar-button">
<i class="fa fa-arrow-left" aria-hidden="true"></i>
</span>
<!-- HEADER -->
<div class="header">
<div class="container">
<div class="row">
<div class="header-message">
<h6><b>Viewer</b></h6>
</div>
<div class="offset-md-3 col-md-6 col-sm-12 offset-sm-0 header-message-container">
<div class="header-message">
<input id="registration-number" class="form-control form-control-sm" type="number" placeholder="Registration number">
</div>
<div class="header-message">
<button id="calculate-button" class="btn btn-sm btn-success">SUBMIT</button>
</div>
</div>
</div>
</div>
</div>
<!-- CARDS -->
<div class="container grade-container" id="result">
<div class="row">
<div class="offset-md-3 col-md-6 col-sm-12 offset-sm-0">
<div class="name" id="name">
</div>
<div class="card shadow-sm">
<div class="gpa-row" id="show-gpa">
</div>
<div class="card-body">
<table id="subject-table" class="table table-striped">
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- JS -->
<script src="js/jquery.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/viewer.js"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-116549528-1');
</script>
</body>
</html>
you can use filter method of javascript;
const allData = [{
"Semester": "07",
"Programme": "BACHELOR OF TECHNOLOGY (ELECTRICAL & ELECTRONICS ENGINEERING)",
"Batch": "2015",
"Examination": "REGULAR December, 2018",
"Institution": "BHARATI VIDYAPEETH COLLEGE OF ENGINEERING",
"CollegeCode": "115",
"EnrollmentNumber": "00211504915",
"Name": "ABHISHEK",
"Marks": [
{
"Id": "49401",
"Credits": "4",
"Internal": "16",
"External": "67",
"Total": 83,
"Grade": "A+",
"Name": "ELECTRICAL DRIVES"
},
{
"Id": "49403",
"Credits": "4",
"Internal": "18",
"External": "60",
"Total": 78,
"Grade": "A+",
"Name": "ADVANCED CONTROL SYSTEMS"
},
{
"Id": "49405",
"Credits": "3",
"Internal": "18",
"External": "56",
"Total": 74,
"Grade": "A",
"Name": "EHV AC AND HVDC TRANSMISSIONS"
}
],
"CreditsSecured": "25",
"_id": "5cd3d6ae390a7a20c80b75f7"
},
{
"Semester": "07",
"Programme": "BACHELOR OF TECHNOLOGY (ELECTRICAL & ELECTRONICS ENGINEERING)",
"Batch": "2015",
"Examination": "REGULAR December, 2018",
"Institution": "BHARATI VIDYAPEETH COLLEGE OF ENGINEERING",
"CollegeCode": "115",
"EnrollmentNumber": "00411504915",
"Name": "AKHIL KHANDELWAL",
"Marks": [
{
"Id": "49401",
"Credits": "4",
"Internal": "19",
"External": "59",
"Total": 78,
"Grade": "A+",
"Name": "ELECTRICAL DRIVES"
},
{
"Id": "49403",
"Credits": "4",
"Internal": "18",
"External": "56",
"Total": 74,
"Grade": "A",
"Name": "ADVANCED CONTROL SYSTEMS"
}
],
"CreditsSecured": "25",
"_id": "5cd3d6ae390a7a20c80b75f8"
}];
var getResult = (regNo) => {
let result = allData.filter(val => val.EnrollmentNumber == regNo); // allData json object array
return result;
}
console.log(getResult("00211504915"));
which json object you are provided i applied filter method and i get expected result. you can try as i mention.
there is allData is an array of objects and we get one object at a time in value argument then compare with regno.

Filter with JSON in angular 6

cities.json
[
{ "id": "1", "name": "Mumbai", "state": "Maharashtra" },
{ "id": "2", "name": "Delhi", "state": "Delhi" },
{ "id": "3", "name": "Bengaluru", "state": "Karnataka" },
{ "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
{ "id": "5", "name": "Hyderabad", "state": "Telangana" },
{ "id": "6", "name": "Chennai", "state": "Tamil Nadu" }
]
mycomponent.html
<div class="search-container">
<h2>Find Location</h2>
<input #searchBoxL id="search-box-loc" (input)="searchForLocation(searchBoxL.value)" [(ngModel)]="selectedResultfilocation"
placeholder="city, province or region" />
<button (click)="searchJobMethod()"><i class="fa fa-search"></i></button>
<ul class="search-result">
<li *ngFor="let loc of searchFindLoopForLocation">
<a (click)="searchBoxL.value = loc;selectedResultfilocation = loc;">{{ loc }}</a>
</li>
</ul>
</div>
mycomponent.ts
selectedResultfilocation: string;
SearchResultResponseForlocation;
searchFindLoopForLocation;
searchForLocation(term: string): void {
this.searchResultMethodForLocation(term);
}
searchResultMethodForLocation(fl: string){
this.http.get('/assets/js/cities.json' + term).pipe(
).subscribe(
data => {
this.SearchResultResponseForlocation = data.json();
console.log(this.SearchResultResponseForlocation[0].name);
this.searchFindLoopForLocation =
this.SearchResultResponseForlocation;
},
error => {
console.log("Error in recieving data");
},
() => {
console.log(this.SearchResultResponse);
}
);
}
My Question is how to filter the name from the given JSON structure in Angular 6. when I will enter location name I can able to get all the recommendations of name. Please help me how to do this, I am totally new in angular 6.
If I'm getting your question right, you don't need something angular specific; You can always filter a JSON in javaScript as follows -
var data = [
{ "id": "1", "name": "Mumbai", "state": "Maharashtra" },
{ "id": "2", "name": "Delhi", "state": "Delhi" },
{ "id": "3", "name": "Bengaluru", "state": "Karnataka" },
{ "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
{ "id": "5", "name": "Hyderabad", "state": "Telangana" },
{ "id": "6", "name": "Chennai", "state": "Tamil Nadu" }
];
var newData = filterData('Mumbai');
function filterData(locationName) {
return data.filter(object => {
return object['name'] == locationName;
});
}
console.log(newData);
If you need help related to implementation, refer the following -
<input #searchBoxL id="search-box-loc" [(ngModel)]="selectedResultfilocation" (ngModelChange)="searchJobMethod()"
placeholder="city, province or region" />
searchJobMethod() {
searchFindLoopForLocation = data.filter(object => {
return object['name'] == selectedResultfilocation;
});
}
Can you try this and let me know... a simple stackblitz would have helped here greatly
/* define SearchResultResponseForlocation as an array... i have used any but you should define a class for your object as per cities.json*/
SearchResultResponseForlocation:any[];
searchResultMethodForLocation(fl: string){
this.http.get('/assets/js/cities.json' + term).pipe(
).subscribe(
data => {
this.SearchResultResponseForlocation = JSON.parse(data);
console.log(this.SearchResultResponseForlocation[0].name);
this.searchFindLoopForLocation =
this.SearchResultResponseForlocation;
},
error => {
console.log("Error in recieving data");
},
() => {
console.log(this.SearchResultResponse);
}
);
}
An example to filter by name
HTML -
<input type="text" [ngModel]="filterBy" (ngModelChange)="filter($event)" />
In a component class -
filterBy: string = "";
filter(value) {
this.filterBy = value;
this.searchFindLoopForLocation = this.searchFindLoopForLocation.filter(obj => obj.name == value);
}
Ts File :
filterSearching() {
this.userList = this.userList.filter(obj => (obj['id'] == this.locationName)||
(obj['email'] == this.locationName) ||(obj['phone_no'] == this.locationName) ||
(obj['first_name'] == this.locationName) || (obj['last_name'] == this.locationName));
}
In the modelChange() function call the original list again . So then When a new value is searched the original data table is showed before clicked Search.
Html :
<div class="col-sm-6 row">
<input type="text" [(ngModel)]="locationName"
(ngModelChange)="modelChange()" />
<button (click)="filterSearching()" >Search</button>
</div>

Showing result from array once then looping through second array

I have two arrays that I am using to simulate two different REST call's JSON response for the time with some static data. One to get the available active categories and another to get all links and then search to find what links go with what category.
The goal here is to build out a navigation that will take each category and display the corresponding links underneath each.
Currently I am unable to get the category to display only once and above the links related to each category then draw the output to the dom once complete.
I tried to use $.one but that did not work. Does anyone have any pointers or suggestions to nudge me in the right direction?
var links = [
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com"
},
"Id": 01,
"Title": "Link 01 - test category 01",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 01"
]
},
"Image": null,
"ID": 01
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 02,
"Title": "Link 02 - test category 01",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 01"
]
},
"Image": null,
"ID": 02
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 03,
"Title": "Link 01 - test category 02",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 02"
]
},
"Image": null,
"ID": 209
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 210,
"Title": "Link 02 - test category 02",
"Link": "https://www.somerandomdomain.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 02"
]
},
"Image": null,
"ID": 210
}
]
//category arr
var categoryArr = [
"Test Category 01",
"Test Category 02",
"Test Category 03"
]
var categoryTitle;
var menu = $("#output2");
$.each(categoryArr, function (catIndex, category) {
$.each(links, function(linkIndex, links) {
if(links.Category.results == category) {
// DOM ELEMENTS
var item = $('<div>').addClass('navContainer'),
title = $('<h4>'),
info = $('<p>'),
link = $('<a>');
// CATEGORY TITLE
info.text(categoryArr[catIndex]); // not showing once per iteration.
// ADD LINKS
link.attr('href',links.Link)
.text(links.Title)
.appendTo(title);
// ADD EVERYTHING
item.append(info,title);
// DISPLAY TO CONTAINER
item.appendTo(menu);
}
})// end glinks
}) // end categoryArr
.navContainer {
border: 1px solid grey;
margin: 10px;
padding:5px;
}
.links ul li {
list-style-type:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output2"></div>
<hr>
<!-- result should be like this -->
<h5>
Result should look like this below
</h5>
<div class="navContainer">
<div class="title">Category title</div>
<div class="links">
<ul>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
</ul>
</div>
</div>
</div>
<div class="navContainer">
<div class="title">Category title</div>
<div class="links">
<ul>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
</ul>
</div>
</div>
</div>
etc.. etc..
You are creating everything inside your inner loop, so for each link you are creating a new item, title, etc.
Also the links.Category.results is an array, whilst you check it as so: links.Category.results == category. To check whether the Category.results contains the category string, you should use indexOf() (or includes(), but it has worse browser support).
Here's a fixed snippet:
var links = [{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com"
},
"Id": 01,
"Title": "Link 01 - test category 01",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 01"
]
},
"Image": null,
"ID": 01
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 02,
"Title": "Link 02 - test category 01",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 01"
]
},
"Image": null,
"ID": 02
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 03,
"Title": "Link 01 - test category 02",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 02"
]
},
"Image": null,
"ID": 209
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 210,
"Title": "Link 02 - test category 02",
"Link": "https://www.somerandomdomain.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 02"
]
},
"Image": null,
"ID": 210
}
]
//category arr
var categoryArr = [
"Test Category 01",
"Test Category 02",
"Test Category 03"
]
var categoryTitle;
var menu = $("#output2");
$.each(categoryArr, function(catIndex, category) {
// DOM ELEMENTS
var $item = $('<div>').addClass('navContainer');
var $title = $('<div>').addClass('title').appendTo($item);
var $links = $('<ul>').appendTo(
$('<div>').addClass('links').appendTo($item)
);
// CATEGORY TITLE
$title.text(category);
$.each(links, function(linkIndex, link) {
var $link = $('<a>');
if (link.Category.results.indexOf(category) != -1) {
// ADD LINKS
$link.attr('href', link.Link)
.text(link.Title)
.appendTo($('<li>').appendTo($links));
}
}) // end glinks
// DISPLAY TO CONTAINER
$item.appendTo(menu);
}) // end categoryArr
.navContainer {
border: 1px solid grey;
margin: 10px;
padding: 5px;
}
.links ul li {
list-style-type: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output2"></div>
<hr>
<!-- result should be like this -->
<h5>
Result should look like this below
</h5>
<div class="navContainer">
<div class="title">Category title</div>
<div class="links">
<ul>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
</ul>
</div>
</div>
<div class="navContainer">
<div class="title">Category title</div>
<div class="links">
<ul>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
</ul>
</div>
</div>
Assign the links first and then do the UI stuff.
var links = [
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com"
},
"Id": 01,
"Title": "Link 01 - test category 01",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 01"
]
},
"Image": null,
"ID": 01
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 02,
"Title": "Link 02 - test category 01",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 01"
]
},
"Image": null,
"ID": 02
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 03,
"Title": "Link 01 - test category 02",
"Link": "https://www.google.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 02"
]
},
"Image": null,
"ID": 209
},
{
"__metadata": {
"id": "",
"uri": "http://www.whatever.com",
"etag": "",
"type": ""
},
"Id": 210,
"Title": "Link 02 - test category 02",
"Link": "https://www.somerandomdomain.com",
"Category": {
"__metadata": {
"type": ""
},
"results": [
"Test Category 02"
]
},
"Image": null,
"ID": 210
}
]
//category arr
var categoryArr = [
"Test Category 01",
"Test Category 02",
"Test Category 03"
]
var categories = categoryArr.map(function(label){
var category = {}
category.label = label
category.links = []
for(var i in links){
if(links[i].Category.results.indexOf(label)!=-1)
category.links.push(links[i])
}
return category
})
var menu = $("#output2");
$.each(categories, function (catIndex, category) {
var item = $('<div>').addClass('navContainer'),
title = $('<h4>'),
linklist = $('<ul>')
title.text(category.label)
$.each(category.links, function(linkIndex, link) {
var li = $('<li>')
// ADD LINK
$('<a>').attr('href',link.Link)
.text(link.Title)
.appendTo(li);
li.appendTo(linklist)
})
// ADD EVERYTHING
item.append(title,linklist);
// DISPLAY TO CONTAINER
item.appendTo(menu);
})
.navContainer {
border: 1px solid grey;
margin: 10px;
padding:5px;
}
.links ul li {
list-style-type:none;
}
a{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output2"></div>
<hr>
<!-- result should be like this -->
<h5>
Result should look like this below
</h5>
<div class="navContainer">
<div class="title">Category title</div>
<div class="links">
<ul>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
</ul>
</div>
</div>
</div>
<div class="navContainer">
<div class="title">Category title</div>
<div class="links">
<ul>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
<li>http://www.google.com</li>
</ul>
</div>
</div>
</div>

Angular bootstrap modal toggle checked for data already present

Firstly i apologize for a lengthy question as i cant post a plunker because this has services which brings data from a backend. Hence i posted as much data as i can as samples.
I have an angular js app that uses bootstrap. I have a modal defined which has the following table:
<div class="panel panel-default" style="float:left;width:525px;">
<div class="panel-body" data-spy="scroll" data-target="#navbar-example" data-offset="0" style="height:200px;overflow:auto;position:relative;">
<table class="table table-hover checkbox">
<tr>
<th>Course</th>
<th>Title</th>
<th>Credits</th>
</tr>
<tr ng-repeat="child in requirements">
{% verbatim %}
<td class="vcenter">
<input type="checkbox" ng-checked="" ng-click="toggleCheck(child)" ng-disabled="required == (planned + completed) && (selectedCourses.indexOf(child) == -1)" value=""/>
{{child.course.subject}}-{{child.course.course_no}}
</td>
<td class="vcenter">{{child.course.course_name}}</td>
{% endverbatim %}
<td class="vcenter">3</td>
</tr>
</table>
</div>
This is how i defined its javascript:
var ModalInstanceCtrl = function (MpttService, PlannedService, RequirementsService, $scope, $http, $log, $modalInstance, mpttid, mpttrequired, mpttcompleted, mpttplanned) {
//debugger
$scope.subcategory = mpttid;
$scope.selectedCourses= [];
$scope.completed = mpttcompleted;
$scope.required = mpttrequired;
$scope.planned = mpttplanned;
MpttService.getMptt(function(data){
$scope.mpttdetails = data;
console.log(data);
});
PlannedService.getPlanned(function(data){
$scope.planneddetails = data;
console.log(data);
});
RequirementsService.getRequirements($scope.subcategory,function(data){
$scope.requirements = data;
console.log(data);
});
angular.forEach(mpttid.subcategory, function(item) {
$scope.selectedCourses.push(item.requirements);
});
$scope.getPercentage = function () {
return (($scope.planned+$scope.completed)/($scope.required)*100).toFixed(2);
}
$scope.toggleCheck = function (course) {
if (($scope.selectedCourses.indexOf(course) === -1)) {
$scope.selectedCourses.push(course);
$scope.planned += 3;
} else {
$scope.selectedCourses.splice($scope.selectedCourses.indexOf(course), 1);
$scope.planned -= 3;
}
$scope.getPercentage();
};
$scope.checkedfunction = function(course){
}
$scope.ok = function () {
//$scope.subcategory.subcategory2 = [];
for(var i = 0; i < $scope.selectedCourses.length; i++){
//$scope.subcategory.subcategory2.push({course: $scope.selectedCourses[i], term:"--",credit:"--",grade:"--"});
var variablesToSend = {
"student": 2773951,
"category": $scope.subcategory,
"course_name": ($scope.selectedCourses[i].course.subject).concat("-",$scope.selectedCourses[i].course.course_no),
"title": $scope.selectedCourses[i].course.title,
"credit": 3,
"term": 'none',
}
$http.post('/api/studentplannedcredit/', variablesToSend).then(function(response){
console.log(response);
//alert('post added');
document.location.reload(true);
}, function(response){
console.log(response);
alert('Unable to add Course');
});
}
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
In this app, when the modal opens, the user can check the courses he wants and save them using the save() function. Since there are limitations on the number of courses to be taken, the table will disable automatically when the required number of courses have been checked.
This is how my json looks like:
Planneddetails:
[
{
"student": 2773951,
"category": 163,
"course_name": "HIST-1301",
"title": "History of the United States I",
"credit": 3,
"term": "2014FA"
},
{
"student": 2773951,
"category": 169,
"course_name": "ANTH-2401",
"title": "Physical Anthropology",
"credit": 3,
"term": "2014SU"
},
{
"student": 2773951,
"category": 169,
"course_name": "ENVR-1402",
"title": "Environmental Science II",
"credit": 3,
"term": "2015SU"
},
{
"student": 2773951,
"category": 157,
"course_name": "HIST-1302",
"title": "History of the United States II",
"credit": 3,
"term": "none"
}
]
MpttDetails:
{
"student_program": {
"academic_program": {
"id": 596,
"program_title": "Associate in Sciences Degree",
"required_credits": 60
},
"id": 3685,
"student": 2773951,
"credits_completed": 26,
"academic_program_gpa": null,
"primary_program": true
},
"category": {
"id": 163,
"name": "CRITICAL READING AND WRITING",
"min_credit": 6,
"parent": {
"id": 162,
"name": "TIER 1 - CORE FOUNDATIONS",
"min_credit": 13,
"parent": {
"id": 149,
"academic_program": null,
"name": "AS.SCIENCE",
"min_credit": 60,
"max_credit": null,
"parent": 128,
"lft": 30,
"rght": 71,
"tree_id": 2,
"level": 1
},
"level": 2
},
"level": 3
},
"student_academic_credit": {
"accad_credit_id": 29328778,
"course": 81,
"student": 2773951,
"course_name": "ENGL-1301",
"title": "Composition I",
"credit": 3,
"final_grade": "C",
"term": "2012FA"
}
},
{
"student_program": {
"academic_program": {
"id": 596,
"program_title": "Associate in Sciences Degree",
"required_credits": 60
},
"id": 3685,
"student": 2773951,
"credits_completed": 26,
"academic_program_gpa": null,
"primary_program": true
},
"category": {
"id": 154,
"name": "CB050",
"min_credit": 3,
"parent": {
"id": 152,
"name": "HUMANITY, CREATIVITY AND THE AESTHETIC EXPERIENCE",
"min_credit": 6,
"parent": {
"id": 150,
"academic_program": null,
"name": "TIER 2 - CORE DOMAINS",
"min_credit": 26,
"max_credit": null,
"parent": 149,
"lft": 41,
"rght": 60,
"tree_id": 2,
"level": 2
},
"level": 3
},
"level": 4
},
"student_academic_credit": {
"accad_credit_id": 29328777,
"course": 209,
"student": 2773951,
"course_name": "ARTS-1301",
"title": "Art Apprec",
"credit": 3,
"final_grade": "A",
"term": "2012FA"
}
},
and my Requirements json:
[
{
"category": 163,
"course": {
"course_id": 1023,
"subject": "HIST",
"course_no": "1301",
"course_name": "History of the United States I",
"title": "History of the United States I",
"local_govt_code": "5401025125",
"academic_level": "CR",
"grade_scheme": "CR",
"credit_type": "I",
"course_type": "1",
"course_level": "1",
"min_credit": 3,
"max_credit": null,
"prereqs": 7,
"cip": "54.0102",
"ceus": "",
"transfer_status": "060"
}
},
{
"category": 163,
"course": {
"course_id": 81,
"subject": "ENGL",
"course_no": "1301",
"course_name": "Composition I",
"title": "Composition I",
"local_govt_code": "2313015112",
"academic_level": "CR",
"grade_scheme": "CR",
"credit_type": "I",
"course_type": "1",
"course_level": "1",
"min_credit": 3,
"max_credit": null,
"prereqs": 5,
"cip": "23.0401",
"ceus": "",
"transfer_status": "010"
}
}
]
The next step was to check all the courses in the table that have already been taken. These details will be retrieved from the mpttdetails and the planneddetails.
So how do i make the modal open with the table having courses already checked for those which are present in the mpttdetails and planned details?
Note: the courses in the $scope.requirements.course.{{subject}}-{{course_no}} needs to be compared with the mpttdetails.student_academic_credit.course_name and the planneddetails.course_name . But i am unable to figure out how to achieve this. Please help!

Categories

Resources