I'm trying to implement this boostrap datatable:
https://datatables.net/examples/api/add_row.html
...but I'd like to add data given by the user in a form rather than pre-set data. I'm storing the form data in localStorage.
I know I need to stringify and parse the data. I've added some pseudocode, along with some commentary as to what I think needs to be done, but I'm stuck.
JSfiddle:
http://jsfiddle.net/wad11656/bkoze96c/8/
HTML:
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Entry Date</th>
<th>Feedback</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Entry Date</th>
<th>Feedback</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>2011/04/25</td>
<td>Different color scheme</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>2011/07/25</td>
<td>Change the menu</td>
</tr>
<tr>
<td>Bob Parker</td>
<td>2014/04/23</td>
<td>Get more sleep--you look awful!</td>
</tr>
<tr>
<td>Wendy-Sue</td>
<td>2014/04/27</td>
<td>Call me more often</td>
</tr>
</tbody>
</table>
<!-- Form -->
<form method="post" action="">
<input name="name" id="name" type="text" class="stored" placeholder="Name" autofocus="" required="">
<br>
<textarea name="feedback" id="feedback" class="stored" placeholder="Endorsement" rows="3" required=""></textarea>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="submit_button" onclick="append_feedback();">Submit</button>
</form>
Javscript:
// Ready Table:
$(document).ready(function () {
var t = $('#example').DataTable();
var counter = 1;
});
// Store data in local storage:
$(document).ready(function () {
function init() {
if (localStorage["name"]) {
$('#name').val(localStorage["name"]);
}
if (localStorage["feedback"]) {
$('#feedback').val(localStorage["feedback"]);
}
}
init();
});
$('.stored').keyup(function () {
localStorage[$(this).attr('name')] = $(this).val();
});
$('#localStorageTest').submit(function () {
localStorage.clear();
});
//Rough draft of Functions for adding row from localStorage data:
/*
var jsonarray = [];
var name;
var feedback;
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var today = month + "/" + day + "/" + year;
var message;
document.getElementById("submit_button").addEventListener("click", submit);
function submit() {
var t = $('#example').DataTable();
t.clear();
// Clear out table with .clear() see api doc
// Grab JSON array
// parse JSON array form local storage to jsonArray
jsonarray = JSON.parse(localStorage.getItem("storage"));
// for each (var message in jsonArray)
//look for how to loop through JSON array in js
endorsements.forEach(var (message)
t.row.add([
message[name],
message[date],
message[feedback], ]).draw();
});
}
function localsave() {
localStorage.Name = document.getElementById("name").value;
localStorage.Words = document.getElementById("feedback").value;
// Put name and message into key value pair for JSON
[{"name":"namethatwasinputeed","date":"1/28/2015","feedback":"messagethatwasinputedfromlocalstorage", },
{"name":"namethatwasinputeed","date":"1/28/2015","feedback":"messagethatwasinputedfromlocalstorage", },
{"name":"namethatwasinputeed","date":"1/28/2015","feedback":"messagethatwasinputedfromlocalstorage", }]
//Stringify to turn into JSON string array
localStorage["storage"] = JSON.stringify(message);
}
*/
LocalStorage has it's own API. You could get unintended results if you don't use it
Basically, you need to do something like this.
if(window.localStorage) { // not all browsers have it
var output;
localStorage.setItem('test', 'value');
output = localStorage.getItem('test');
console.log(output); // value
}
You could also checkout a library called Kizzy which does localStorage well
For you're issue, you should try putting everything inside a document.ready along with all your other commented code, or jQuery will not work properly
// Ready Table:
$(document).ready(function () {
var t = $('#example').DataTable();
var counter = 1;
function init() {
if (localStorage["name"]) {
$('#name').val(localStorage["name"]);
}
if (localStorage["feedback"]) {
$('#feedback').val(localStorage["feedback"]);
}
}
init();
$('.stored').keyup(function () {
localStorage[$(this).attr('name')] = $(this).val();
});
$('#localStorageTest').submit(function () {
localStorage.clear();
});
});
Related
I am working on angular website where I need to export table's data to pdf.
I want to use jQuery datatables for it as it alse add some more features like paging,searching and sorting, but getting this error "Error: [$injector:unpr]" on browser's console, even I am not sure using ng-table will make it to datatable or not.
I have also tried using jquery plugin pdfmake but it only make signle page pdf and failed if table have larger data.
Please help and TIA.
Html :-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.min.js"></script>
<table id="myYealyGrid" ng-class="myYealyGridClass" class="table table-responsive gridtable" ng-table="yearly_Table">
<thead>
<tr>
<th>Customer Name</th>
<th>Year</th>
<th>Total Amount($)</th>
</tr>
</thead>
<tbody>
<tr ng-show="YearlyReport.length !=0" ng-repeat="reportrow in YearlyReport" ng-init="setTotal(reportrow)">
<td>{{reportrow.CustomerName}}</td>
<td>{{reportrow.Month}}</td>
<td>{{reportrow.TotalAmount}}</td>
</tr>
<tr ng-show="YearlyReport.length ==0">
<td><small class="nodata">No data found.</small></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot>
<tr ng-show="YearlyReport.length !=0" class="bg-warning">
<td class="td-font-bold-custm">Total</td>
<td></td>
<td class="td-font-bold-custm">{{gridTotalAmount | number:2}}</td>
</tr>
</tfoot>
</table>
AngularJs:-
var appKitchenOrderReport = angular.module("myKitchenOrderReportApp", ['ngTable']);
appKitchenOrderReport.controller("myKitchenOrderReportCntrl", function ($scope, $window, $timeout, myKitchenOrderReportService, ngTableParams) {
var getData = myKitchenOrderReportService.SearchData($scope.CustomerName, $scope.Year);
getData.then(function (kitchenreportdata) {
var yearlyGridData = kitchenreportdata.data.OrderYearlyReport;
$scope.yearly_Table = new ngTableParams({
page: 1,
count: 10
}, {
total: $scope.yearlyGridData.length,
getData: function ($defer, params) {
$scope.YearlyReport = $scope.yearlyGridData.slice((params.page() - 1) * params.count(), params.page() * params.count());
$defer.resolve($scope.YearlyReport);
}
});
}, function () {
alert('Error in getting data');
});
});
appKitchenOrderReport.service("myKitchenOrderReportService", function ($http) {
this.getKitchenOrderReportData = function () {
var response = '';
return $http.get("GetOrderReport"); };
this.SearchData = function (CustomerName, Year)
{
var GetParams = new Object();
GetParams.CustomerName = CustomerName;
GetParams.Year = Year
var response = $http({
method: "post",
url: "GetOrderReport",
data: '{model: ' + JSON.stringify(GetParams) + '}',
});
return response;
}
});
you can Use $('#myYealyGrid').DataTable(); to initialize your datatable .
But Use just befor , when you Put data into the HTML table .
It will automatically initialize your Datatable.
Try it and let me know is it working or not .
This question already has an answer here:
Angular JS firebase.(child_added) not rendering on page
(1 answer)
Closed 5 years ago.
I am building an app that gets its objects from a Firebase database. The problem is that when I try to iterate what I got, it doesn't show anything. However, when I ask to display it via console.log it's there!
I guess it is because of an HTTP method and its promise. But I haven't figured out how to solve it. Could someone please help me understand it?
HTML:
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="profile in profiles">
<td>{{profile.value.id}}</td>
<td>{{profile.value.name}}</td>
<td>{{profile.value.description}}</td>
<td>{{profile.value.price | currency}}</td>
<td>
<button type="button" class="btn">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
Controller.js
App.controller("adminController", function($scope) {
console.log("running");
var profiles = new Array;
var query = firebase.database().ref("profiles").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
profiles.push({
key: key,
value: JSON.parse(childData)
})
});
console.log(profiles);
});
}
You need to use $scope.profiles with your controller,
App.controller("adminController", function($scope) {
console.log("running");
$scope.profiles = [];
var query = firebase.database().ref("profiles").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
$scope.profiles.push({
key: key,
value: JSON.parse(childData)
})
});
console.log($scope.profiles);
});
}
JSP file
<div class="container">
<table id="headerTable" class="table table-bordered">
<thead>
<tr>
<th colspan="2">Header</th>
</tr>
</thead>
<tbody>
<c:forEach items="${headerList}" var="field">
<tr>
<th>${field}</th>
<td><input id="${field}" type="text" class="form-control "></td>
</tr>
</c:forEach>
</tbody>
</table>
Javascript
$('#parseBtn').click(function() {
var parseMsg = $('#msgText').val();
alert("parse message is " + parseMsg);
$.ajax({
type: "GET",
url: "/parseMessage",
data: {
"msg": parseMsg
},
success: function(data) {
//data format looks like Object {SubsystemChannel: "F", MessageNumber: "200257", DebugQueue: " ", WorkStationNumber: "023", FrontEndNumber: "0000"…}
$('#headerTable input').each(function() {
var id = $(this).attr('id');
var field = data.id;
$(this).val(field);
});
}
});
});
What I am going to do is, go through the $('#headerTable input'), set the value(from data) in it. So, I get the each input id first, then get the value from data using id, but it failed.... Could you help me on this? thank you very much
You should use Bracket notation instead of dot notation to access properties using id variable
$('#headerTable input').each(function () {
var field = data[$(this).attr('id')];
$(this).val(field);
});
Suppose you have a html table of the
<form id="myForm">
<table id="myTable">
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
<tr>
<td>Alpha</td>
<td>Bravo</td>
<td>X</td>
</tr>
<tr>
<td>Charlie</td>
<td>Delta</td>
<td>X</td>
</tr>
<tr>
<td>Echo</td>
<td>Foxtrot</td>
<td>X</td>
</tr>
</table>
</form>
Reset
I have the following javascript
var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;
function remove(rowID)
{
table.deleteRow(rowID);
}
function reset()
{
form.innerHTML = formSave;
}
For some reason, the remove() function works fine, but after using the reset() function, it no longer works. Can anyone tell me why this is?
As var table is a live 'Element object' it's properties are updated each time you delete a row. By the time you deploy the reset() function var table references less Children than the restored HTML. Opening the console will show you have an indexing error on subsequent uses of the function bound to "X".
You can remedy this by re-acquiring the element in the reset function, like so...
var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;
function remove(rowID) {
table.deleteRow(rowID);
}
function reset() {
form.innerHTML = formSave;
/* re-acquire 'new' (inserted) table */
table = document.getElementById('myTable');
}
Hope that helped :)
Hope you are doing good..
I'm trying to fetch single record from datasource by Id in UI via Angular-js.
Using Web-API for retrieving values from DB.
To make it simple : HTML-->Angular-->WebAPI-->DB
When i'm trying it says Id passed is Null..Don't know how to rectify.
hope i've missed to fill hole in somewhere....below snippets fr ref.
(Also can u verify/correct me the way i've coded in html is right way to display values fetched by Id)
HTML :
<div ng-controller="SingleController">
<input type="text" ng-model="_Id" />
<input type="button" value="search" ng-click="search()" />
<table>
<tr>
<td>MovieId</td>
<td>{{MovID}}</td>
</tr>
<tr>
<td>Title</td>
<td>{{Movtitle}}</td>
</tr>
<tr>
<td>Genre</td>
<td>{{Movgnre}}</td>
</tr>
<tr>
<td>Classification</td>
<td>{{Movcls}}</td>
</tr>
<tr>
<td>ReleaseDate</td>
<td>{{Movdate}}</td>
</tr>
<tr>
<td>Rating</td>
<td>{{Movrate}}</td>
</tr>
<tr>
<td>Cast</td>
<td>{{Cast}}</td>
</tr>
</table>
</div>
Controller.JS
app.controller('SingleController', function ($scope, MyService) {
var Id = $scope._Id;
$scope.search = function (Id) {
var promiseGetSingle = MyService.getbyId(Id);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.MovID = res._movieId;
$scope.Movtitle = res._title;
$scope.Movgnre = res._genre;
$scope.Movcls = res._classification;
$scope.Movdate = res._releaseDate;
$scope.Movrate = res._rating;
$scope.Cast = res._cast;
// $scope.IsNewRecord = 0;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
}
});
service.js
this.getbyId = function (Id) {
return $http.get("/api/values/" + Id);
};
Please ignore this lengthy snippets.
Could you please help me on this.
Your search function is expecting you to pass a value when it is invoked on ng-click:
<input type="button" value="search" ng-click="search(_Id)" />