This is creating my table and working - It creates a table and I am going to have it check a list to hide columns. For testing purposes I am trying to hide the colun "Proj_Type" it does hide the header but does not hide the actual column of data. I want the entire thing to hide.
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table/>', {
'class': 'GRD1',
id: id + "GRDMKTLIST",
}
)
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (d) {
var data = $.parseJSON(d.d);
var colHeader = Object.keys(data[0]);
for (var i = 0; i < colHeader.length; i++) {
if (colHeader[i] != "notes") {
$tbody.append("<th>" + colHeader[i] + "</th>");
}
}
//sets new line
$tbody.append('<tr />').children('tr:last')
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < colHeader.length; j++) {
if (colHeader[j] != "notes") {
$tbody.append('<td>' + data[i][colHeader[j]] + '</td>');
}
}
$tbody.append('<tr />').children('tr:last')
}
setTimeout(function () {
}, 1000);
}
});
$($table.find('th')).each(function () {
var indextest = $(this).index() + 1;
if ($(this).text() == "Proj_Type") {
$('[id*=GRDMKTLIST] td:nth-child(' + indextest + '),th:nth-child(' + indextest + ')').hide();
}
})
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
However, on the bottom where i have
if ($(this).text() == "Proj_Type") {
$('[id*=GRDMKTLIST] td:nth-child(' + indextest + '),th:nth-child(' + indextest + ')').hide();
}
This only hides the header and I am trying to hide the entire column TD included.
There are two main issues:
$('[id*=GRDMKTLIST]
will look in the DOM, but your $table has not yet been added to the DOM, so does nothing. Use $table.find(... to use the $table variable in memory.
$tbody.append('<td
will append the td (and equivalent code for th) to the tbody - but these should be in a tr.
The browser will do some "magic" and see an empty <tr></tr> and put a new row in for you, but selectors for tbody > tr > td won't work. This also means there's only a single :nth-child(n) per n, not per row (as all cells across all rows are siblings).
You can add a new row to $tbody and return the new row by using .appendTo
$tr = $("<tr>").appendTo($tbody);
then add the th/td to $tr and not $tbody
$tr.append('<td...`
Regarding the selector for $table.find("td,th") you don't need the th part as you're looping th and it's already this, so you can do:
$(this).hide();
$table.find('td:nth-child(' + indextest + ')').hide();
Also make sure you only create tr as you need it. Your code create a tr before the data row loop and inside the data row loop, leaving an empty tr.
for (var i = 0; i < data.length; i++) {
$tr = $("<tr>").appendTo($tbody);
for (var j = 0; j < colHeader.length; j++) {
if (colHeader[j] != "notes") {
$tr.append('<td id=' + colHeader[j] + '>' + data[i][colHeader[j]] + '</td>');
}
}
}
Also updated in the fiddle: https://jsfiddle.net/n168ra2g/3/
Possible duplicate Nested elements
I'm getting from server-side ajax response (Json) and I'm trying to dynamically create table rows and append them to an existing table with id=records_table.
I tried to implement the solution in possible duplicate but it failed.
My response looks like that:
'[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]'
the require result is something like that:
<tr>
<td>9</td>
<td>Alon</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>Tala</td>
<td>5</td>
</tr>
I want to do something without parsing the Json so I tried to do the following, which of course was a disaster:
function responseHandler(response)
{
$(function() {
$.each(response, function(i, item) {
$('<tr>').html(
$('td').text(item.rank),
$('td').text(item.content),
$('td').text(item.UID)
).appendTo('#records_table');
});
});
}
From my solution I get only one row with the number 6 in all cells. What am I doing wrong?
Use .append instead of .html
var response = "[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]";
// convert string to JSON
response = $.parseJSON(response);
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.rank),
$('<td>').text(item.content),
$('<td>').text(item.UID)
); //.appendTo('#records_table');
console.log($tr.wrap('<p>').html());
});
});
Try this (DEMO link updated):
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
Fiddle DEMO WITH AJAX
Here is a complete answer from hmkcode.com
If we have such JSON data
// JSON Data
var articles = [
{
"title":"Title 1",
"url":"URL 1",
"categories":["jQuery"],
"tags":["jquery","json","$.each"]
},
{
"title":"Title 2",
"url":"URL 2",
"categories":["Java"],
"tags":["java","json","jquery"]
}
];
And we want to view in this Table structure
<table id="added-articles" class="table">
<tr>
<th>Title</th>
<th>Categories</th>
<th>Tags</th>
</tr>
</table>
The following JS code will fill create a row for each JSON element
// 1. remove all existing rows
$("tr:has(td)").remove();
// 2. get each article
$.each(articles, function (index, article) {
// 2.2 Create table column for categories
var td_categories = $("<td/>");
// 2.3 get each category of this article
$.each(article.categories, function (i, category) {
var span = $("<span/>");
span.text(category);
td_categories.append(span);
});
// 2.4 Create table column for tags
var td_tags = $("<td/>");
// 2.5 get each tag of this article
$.each(article.tags, function (i, tag) {
var span = $("<span/>");
span.text(tag);
td_tags.append(span);
});
// 2.6 Create a new row and append 3 columns (title+url, categories, tags)
$("#added-articles").append($('<tr/>')
.append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
.append(td_categories)
.append(td_tags)
);
});
Try it like this:
$.each(response, function(i, item) {
$('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table');
});
Demo: http://jsfiddle.net/R5bQG/
$.ajax({
type: 'GET',
url: urlString ,
dataType: 'json',
success: function (response) {
var trHTML = '';
for(var f=0;f<response.length;f++) {
trHTML += '<tr><td><strong>' + response[f]['app_action_name']+'</strong></td><td><span class="label label-success">'+response[f]['action_type'] +'</span></td><td>'+response[f]['points']+'</td></tr>';
}
$('#result').html(trHTML);
$( ".spin-grid" ).removeClass( "fa-spin" );
}
});
You shouldn't create jquery objects for each cell and row. Try this:
function responseHandler(response)
{
var c = [];
$.each(response, function(i, item) {
c.push("<tr><td>" + item.rank + "</td>");
c.push("<td>" + item.content + "</td>");
c.push("<td>" + item.UID + "</td></tr>");
});
$('#records_table').html(c.join(""));
}
Data as JSON:
data = [
{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}
]
You can use jQuery to iterate over JSON and create tables dynamically:
num_rows = data.length;
num_cols = size_of_array(data[0]);
table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");
header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);
$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})
Here is the size_of_array function:
function size_of_array(obj) {
size = Object.keys(obj).length;
return(size)
};
You can also add styling if needed:
$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');
Result:
This is working sample that I copied from my project.
function fetchAllReceipts(documentShareId) {
console.log('http call: ' + uri + "/" + documentShareId)
$.ajax({
url: uri + "/" + documentShareId,
type: "GET",
contentType: "application/json;",
cache: false,
success: function (receipts) {
//console.log(receipts);
$(receipts).each(function (index, item) {
console.log(item);
//console.log(receipts[index]);
$('#receipts tbody').append(
'<tr><td>' + item.Firstname + ' ' + item.Lastname +
'</td><td>' + item.TransactionId +
'</td><td>' + item.Amount +
'</td><td>' + item.Status +
'</td></tr>'
)
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
}
// Sample json data coming from server
var data = [
0: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test1", Lastname: "Test1", }
1: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test 2", Lastname: "Test2", }
];
<button type="button" class="btn btn-primary" onclick='fetchAllReceipts("#share.Id")'>
RECEIPTS
</button>
<div id="receipts" style="display:contents">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Transaction</th>
<th>Amount</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I have created this JQuery function
/**
* Draw a table from json array
* #param {array} json_data_array Data array as JSON multi dimension array
* #param {array} head_array Table Headings as an array (Array items must me correspond to JSON array)
* #param {array} item_array JSON array's sub element list as an array
* #param {string} destinaion_element '#id' or '.class': html output will be rendered to this element
* #returns {string} HTML output will be rendered to 'destinaion_element'
*/
function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) {
var table = '<table>';
//TH Loop
table += '<tr>';
$.each(head_array, function (head_array_key, head_array_value) {
table += '<th>' + head_array_value + '</th>';
});
table += '</tr>';
//TR loop
$.each(json_data_array, function (key, value) {
table += '<tr>';
//TD loop
$.each(item_array, function (item_key, item_value) {
table += '<td>' + value[item_value] + '</td>';
});
table += '</tr>';
});
table += '</table>';
$(destinaion_element).append(table);
}
;
You could do it something like this:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function(){
$.ajax({
url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
data: '<any parameters you want to send as the Request body or query string>',
dataType: json,
async: true,
method: "GET"
success: function(data){
//If the REST API returned a successful response it'll be stored in data,
//just parse that field using jQuery and you're all set
var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td>' + value + '</td>';
});
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('#tblSomething').html(tblSomething);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
});
</script>
<table id = "tblSomething" class = "table table-hover"></table>
jQuery.html takes string or callback as input, not sure how your example is working... Try something like $('<tr>').append($('<td>' + item.rank + '</td>').append ...
And you have some definite problems with tags fromation. It should be $('<tr/>') and $('<td/>')
I do following to get JSON response from Ajax and parse without using parseJson:
$.ajax({
dataType: 'json', <----
type: 'GET',
url: 'get/allworldbankaccounts.json',
data: $("body form:first").serialize(),
If you are using dataType as Text then you need $.parseJSON(response)
I am having a html table getting populated using JSON by an ajax call as follows -
$.ajax({
type: "POST",
url: "my_url",
data: JSON.stringify(result),
async: true,
dataType: "json",
contentType: "application/json; charset= Shift-JIS",
success: function (response) {
glResp = response;
populateTable(glResp);
},
error: function (error) {
console.log(error);
//alert("Error!!");
}
});
The function used for populating the table is as follows -
function populateTable(finalObject) {
var obj = finalObject;
var headers1 = ['Name', 'ID', 'Job', 'Salary','JoiningDate'];
var table = $("<table id='my-table' />");
var columns = headers1;
columns.unshift('');
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
if (i == 0) {
var headerCell = $("<th><input type='button' id='sort'></th>");
row.append(headerCell);
}
else {
var headerCell = $("<th/>");
headerCell.html([columns[i]]);
row.append(headerCell);
}
}
$.each(obj, function (i, obj) {
$row = '<tr><td><input type="checkbox"></td><td>' + obj.Name + '</td><td>' + obj.ID+ '</td><td>' + obj.Job + '</td><td>' + obj.Salary + '</td><td>'+ obj.JoiningDate+'</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
Now I want to enable sorting for only two columns - ID & JoiningDate using DataTable plugin. I tried to understand the api but everytime something or the other problem came up. (E.g. for ID = M981-01) (E.g. for date: 2016-10-24) Can anyone help me to implement DataTable plugin or any other suitable approach to enable sort with respect to ID and JoiningDate?
As you can see I have this function:
var review = function() {
$('a[name=review_button]').live("click", function (e) {
e.preventDefault();
/*
* #array of reservations
* #all of the fields
*/
var $tr_options = '';
var reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
reservations[i] = $(selected).text();
});
var amount = $('input[name=amount-price]').val();
var currency_value = $('input[name=currency-value]').val();
var currency_name = $('.currency_appendto option:selected').html();
var actual_amount = $('input[name=actual-amount]').val();
var actual_remaining = $('input[name=actual-remaining]').val();
var funds_arrival_date = $('input[name=funds-arrival]').val();
var paid_to = $('.paidto option:selected').html();
var checkbox = $('.multi-transaction:checked').map(function () {
return this.value
}).get();
var options = troptions(reservations, amount, currency_name, currency_value, actual_amount, actual_remaining, funds_arrival_date, paid_to);
$.each(options, function (k, v) {
$tr_options += '<tr>' + '<td>' + k + '</td>' + '<td>' + v + '</td>' + '</tr>';
}); //one line creating trs awesome
var appendto = (
'<table class="table table-striped mb-none">' + '<thead>' +
'<tr>' + '<th>Information</th>' + '<th>Values</th>' + '</tr>' +
'</thead>' +
'<tbody>' + $tr_options + '</tbody>' +
'</table>'
);
$('[name=review-information]').html(appendto);
});
$('button[name=submit-transaction]').live("click", function (e) {
e.preventDefault();
$.ajax({
url: '/transactions/submit',
type: 'POST',
data: {
amount: $('input[name=amount-price]').val(),
currency_value: $('input[name=currency-value]').val(),
currency_name: $('.currency_appendto option:selected').html(),
actual_amount: $('input[name=actual-amount]').val(),
actual_remaining: $('input[name=actual-remaining]').val(),
funds_arrival_date: $('input[name=funds-arrival]').val(),
paid_to: $('.paidto option:selected').html(),
},
success: function (data) {
console.log(data);
}
});
});
}
review();
$(".date-mask").inputmask("d/m/y",{ "placeholder": "dd/mm/yyyy" });
$(".amount-czk").inputmask('integer', { rightAlign: false });
});
Where i have all of those values:
var reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
reservations[i] = $(selected).text();
});
var amount = $('input[name=amount-price]').val();
var currency_value = $('input[name=currency-value]').val();
var currency_name = $('.currency_appendto option:selected').html();
var actual_amount = $('input[name=actual-amount]').val();
var actual_remaining = $('input[name=actual-remaining]').val();
var funds_arrival_date = $('input[name=funds-arrival]').val();
var paid_to = $('.paidto option:selected').html();
And i need to reuse them in multiple areas of the app, however i don't want to re-write those elements all of the time. Writing those values outside the review function returns the .val(); of unidentified. as those values always change .. How can i make a function that will give me back access to all of those values upon call?
Just return them as properties of an Object
function getValues() {
var o = {};
o.reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
o.reservations[i] = $(selected).text();
});
o.amount = $('input[name=amount-price]').val();
o.currency_value = $('input[name=currency-value]').val();
o.currency_name = $('.currency_appendto option:selected').html();
o.actual_amount = $('input[name=actual-amount]').val();
o.actual_remaining = $('input[name=actual-remaining]').val();
o.funds_arrival_date = $('input[name=funds-arrival]').val();
o.paid_to = $('.paidto option:selected').html();
return o;
}
Then access as
var values = getValues();
values.actual_amount; // foo
i am new to mvc and jquery,
i have created one table with jquery but i don't know how we add one actionlink in each row and also i need to call one function on the onclick event.
my code is given bellow
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td>' + '#Html.ActionLink("Edit", "Edit", new { id = val.empID })' + '</td>');
tab.append(trow);
});
here i got one error
"val is not in the current context"
please anyone help me to add one actionlink with click event.
You can achieve this by changing your code as below.
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td></td>');
tab.append(trow);
});
Try this and let me know, if you required anymore information.
Below Code Work Perfectly and Bind Table dynamically with Control.
function bindTable (data)
{
usersTable = $('<table><thead><tr>'
+ '<th style="width: 300px;">Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th>'
+ '</tr></thead ></table>').attr({ class: ["dataTable row-border hover"].join(' '), id: "table", style: "border: 1px solid; background-color:#d2d2d2;" });
var rows = new Number("10");
var cols = new Number("4");
var tr = [];
if (data != null) {
for (var i = 0; i < data.length; i++) {
var row = $("<tr></tr>").attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(table);
$("<td></td>").html(data[i].Col1).appendTo(row);
$("<td></td>").html(data[i].Col2).appendTo(row);
$("<td></td>").html(data[i].Col3).appendTo(row);
$("<td></td>").html(data[i].Col4).appendTo(row);
$("<td></td>").html($('<a href=/ControllerName/Action?ParamId='+data[i].Id+'>Action</a>')).appendTo(row);
}
}
table.appendTo("#Div");
$("#table").DataTable({
"aoColumns": [null, null, null, null, { "bSortable": false }]
});
}