1.This is my code for my HTML table where I'm unable to display the data from it using my javascript code below.
<table id="empTable">
<tr>
<th>Type</th>
<th>SimiScore</th>
<th>Rank</th>
<th>Introversion/Extraversion</th>
<th>Intuitive/Observant</th>
<th>Thinking/Feeling</th>
<th>Judging/Perceiving</th>
</tr>
{% for doc in docs %}
<tr>
<td>{{doc["type"]}}</td>
<td>{{doc["Simiscore"]}}</td>
<td>{{doc["Rank"]}}</td>
<td>{{doc["Introversion/Extraversion"]}}</td>
<td>{{doc["Intuitive/Observant"]}}</td>
<td>{{doc["Thinking/Feeling"]}}</td>
<td>{{doc["Judging/Perceiving"]}}</td>
</tr>
{% endfor %}
</table>
<p><input type="button" id="bt" value="Show Table Data" onclick="showTableData()" /></p>
<p id="info"></p>
2.This is my javascript code to display the data, but I'm unable to display it
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.innerHTML = info.innerHTML + '<br />'; // ADD A BREAK (TAG).
}
}
</script>
{
$(document).ready(function()
{
$.ajax({
url: "getjson.php",
type: "POST",
dataType:"json",
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value.id +
'</td><td>' + value.konu +
'</td><td>' + value.aciklama +
'</td><td>' + value.giris_tarih +
'</td><td>' + value.degistirilme_tarih +
'</td><td>' + value.ad_soyad +
'</td><td>' + value.email +
'</td></tr>';
});
$('#records_table').append(trHTML);
}
});
});
}
this is an example you can use
Related
When I am deleting row from my table, also the table header is being deleted, how I can fix this?
$('#clubs tbody').on('click', '.deleteBtn', function() {
$(this).closest('tr').remove();
});
Button tag
<td>
<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"
title=#DbResHtml.T("Delete", "Resources")></button>
</td>
My button have a class of .delete so when I click it, my row is deleted together with my table header.
My table have and id of clubs while table body have and id of clubsTBody.
Table
<div class="table-responsive">
<table class="table table-striped my-4 " id="clubs">
<thead>
<tr>
<th>#DbResHtml.T("#", "Resources")</th>
<th>#DbResHtml.T("Клуб", "Resources")</th>
<th>#DbResHtml.T("Лига", "Resources")</th>
<th></th>
</tr>
</thead>
<tbody id="clubsTBody">
#foreach (var club in Model.Player.PlayerClubs)
{
<tr>
<td>#Html.DisplayFor(x => count)</td>
<td>#Html.DisplayFor(x => club.Club.Name)</td>
<td>#Html.DisplayFor(x => club.Club.League.LeagueType)</td>
<td>
<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn"
title=#DbResHtml.T("Delete", "Resources")></button>
</td>
</tr>
count++;
}
</tbody>
</table>
</div>
Also I am adding dynamically rows into my table.
$(document).ready(function() {
$('#select2-3').change(function() {
var cc = $('#select2-3').val();
var ids = [];
for (let i = 0; i < cc.length;i++) {
ids.push(cc[i]);
}
$.ajax({
type : "POST",
url : "#Url.Action("GetClubsById","Player")",
data : {"ids": ids},
success : function(data) {
console.log(data);
$('#clubs tr').remove();
var counter = 1;
for (let i = 0; i < data.length; i++) {
$("#clubsTBody").append("<tr><td>" + counter + "</td>"
+ "<td>" + data[i].name + "</td>"
+ "<td>" + data[i].league.leagueType + "</td>"
+ "<td>" + '<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn" title=#DbResHtml.T("Delete", "Resources")></button>' + "</td>"
+ "</tr >");
counter++;
}
},
error: function(req, status, error) {
console.log(msg);
}
});
$('.deleteBtn').on('click', function() {
$(this).closest('tr').remove();
var value = $(this).closest('tr').children('td:eq(1)').text();
$(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
});
})
// /.../
})
The problem is here, when I am removing selected item from select list, without this code, everything is working perfectly but selected items doesn't get deselected.
$(`#select2-3 option:selected:contains("${value}")`)
.prop("selected", false)
.parent()
.trigger("change");
$(document).ready(function() {
$('#select2-3').change(function() {
var cc = $('#select2-3').val();
var ids = [];
for (let i = 0; i < cc.length;i++){
ids.push(cc[i]);
}
$.ajax({
type: "POST",
url: "#Url.Action("GetClubsById","Player")",
data: {"ids": ids},
success: function(data) {
console.log(data);
$('#clubsTBody tr').remove();
var counter = 1;
for (let i = 0; i < data.length; i++) {
$("#clubsTBody").append("<tr><td>" + counter + "</td>"
+ "<td>" + data[i].name + "</td>"
+ "<td>" + data[i].league.leagueType + "</td>"
+ "<td>" + '<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn" title=#DbResHtml.T("Delete", "Resources")></button>' + "</td>"
+ "</tr >");
counter++;
}
},
error: function(req, status, error) {
console.log(msg);
}
});
$('.deleteBtn').on('click', function() {
$(this).closest('tr').remove();
var value = $(this).closest('tr').children('td:eq(1)').text();
$(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
});
});
You nee to write this: $('#clubsTBody tr').remove(); instead of $('#clubs tr').remove();
You are removing all the TR in Ajax Response instead of Only Body TRs
I am having a html table which is being dynamically populated via JSON data. I have to implement pagination to this table in order to show only 10 records per page.
I have tried Datatable.js and smpSortaableTable.js which shows the option for previous and next button but all the records are shown on first page only.
Libraries:
<link rel="stylesheet" href="smpSortableTable.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="smpSortableTable.js"></script>
Table design is:
<div class="card-body">
<table class="table table-bordered table-hover order-list table-responsive-sm table-responsive-md table-striped" style="font-size:small;" id="Open_table">
<thead class="thead-dark">
<tr>
<th>TAF-No</th>
<th>Purpose</th>
<th>Travel Location</th>
<th>No of Days</th>
<th>Advance</th>
<th>Remarks</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Javascript code:
<script>
var name1 = "<%= Request.Cookies["emailid"].Value.ToString() %>";
//alert(name1);
var dtt = document.getElementById("year_date").value;
//alert(dtt);
var tafid;
if (document.getElementById("open_taf").value == "") {
tafid = 0;
var myObj;
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open("GET", "API");
request.send();
request.onload = function () {
var superHero = request.response;
myObj = JSON.parse(superHero);
myObj = JSON.parse(myObj);
//var counter = myObj.count;
for (i in myObj.open_list) {
check3(i, myObj.open_list[i].taf_no, myObj.open_list[i].purpose, myObj.open_list[i].loc_of_vst, myObj.open_list[i].no_of_days, myObj.open_list[i].adv_amt, myObj.open_list[i].remarks, myObj.open_list[i].tid, name1);
}
}
}
else {
tafid = document.getElementById("open_taf").value;
var myObj;
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open("GET", "API");
request.send();
request.onload = function () {
var superHero = request.response;
myObj = JSON.parse(superHero);
myObj = JSON.parse(myObj);
//var counter = myObj.count;
//alert(counter);
for (i in myObj.open_list) {
check3(i, myObj.open_list[i].taf_no, myObj.open_list[i].purpose, myObj.open_list[i].loc_of_vst, myObj.open_list[i].no_of_days, myObj.open_list[i].adv_amt, myObj.open_list[i].remarks, myObj.open_list[i].tid, name1);
}
}
}
}
function check3(counter, data, data1, data2, data3, data4, data5, data6, data7, data8) {
//alert('2');
var newRow = $("<tr>");
var cols = "";
cols += '<td name="name' + counter + '">' + data + '</td>';
cols += '<td name="from_loc' + counter + '">' + data1 + '</td>';
cols += '<td name="to_loc' + counter + '">' + data2 + '</td>';
cols += '<td name="date_of_travel' + counter + '">' + data3 + '</td>';
cols += '<td name="status' + counter + '">' + data4 + '</td>';
cols += '<td name="status' + counter + '">' + data5 + '</td>';
cols += '<td>Details</td>';
newRow.append(cols);
$("table.order-list").append(newRow);
$('#Open_table').smpSortableTable(check3,5);
}
</script>
Expected result is page numbers and previous and next button at the bottom. Please guide and thank you in advance for your help.
After including the Datatable.js in your file. You need to apply that DataTable on your table in ready() function. Try this..
$(document).ready( function () {
$('#Open_table').DataTable();
} );
This is my function to get some data from a database table and put checkboxes a page.
function myfunction() {
var dataObject = {};
$.ajax({
url: "http://localhost:45217/api/Symptom/LoadSymptom",
type: "GET",
data: JSON.stringify(dataObject),
contentType: "application/json",
success: function (response) {
for (var i = 0; i < response.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + response[i].SymptomName + "</td>");
tr.append("<td>" + "<input type=checkbox tr.id=" + i + " value=" + i + ">" + "</td>");
$('table').append(tr);
}
}
});
}
How I pass this checkbox values to server.
http://api.jquery.com/jquery.post/
$.post( "YourServerPageToProcessData.php", function( dataToSendToServer ) { /* client action on success or error here */ });
-- have you tried that?
In order to make an Ajax request each time user clicks on checkbox, you can do that in 2 ways-
Define function you want to perform onClick-
function someFn() {
// perform some Ajax request
}
Method 1:
for (var i = 0; i < response.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + response[i].SymptomName + "</td>");
tr.append('<td><input type=checkbox id="' + i + '" value=' + i + ' onclick="someFn()"></td>');
$('table').append(tr);
}
Method 2:
$('input[id^="symptom_chkbox_"]').on('click', function(){
// perform some Ajax request
})
for (var i = 0; i < response.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + response[i].SymptomName + "</td>");
tr.append('<td><input type="checkbox" id="symptom_chkbox_' + i + '" value=' + i + '></td>');
$('table').append(tr);
}
I am populating a html table using an Ajax call. Every time I click on Upload button which re-populates the table, the top header row shifts right. How can I ensure it actually does not happen ?
HTML -
<input type="button" id="upload" value="Upload" class="btn btn-primary custom-button-width .navbar-right" />
<div id="hello" style="position: relative; margin-top: -10px; overflow: auto; width: 100%; max-height: 550px; align-self: center; overflow: auto;">
</div>
JS-
function populateTable(finalObject) {
var headers1 = ["Name1","Name2","Name3","Name4","Name5","Name6",
"Name7","Name8","Name9","Name10",
];
var obj = resp;
var table = $("<table id='my-table' />");
headers1.splice(6, 0, "New Name");
var columns = headers1;
columns.unshift('');
var columnCount = columns.length;
var thead = $('<thead/>');
var row_head = $('<tr/>');
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th/>");
if (i == 0) {
headerCell.html("<span id='sort'>キャンセル</span>");
}
else if (i == 15|| i==17) {
headerCell.html([columns[i]]);
headerCell.addClass("sortable");
}
else {
headerCell.html([columns[i]]);
}
row_head.append(headerCell);
}
thead.append(row_head);
table.append(thead);
var tbody = $('<tbody/>');
$.each(obj, function (i, obj) {
var row = '<tr ><td><input type="checkbox" value=' + obj.Name1 + '></td><td>' + ReplaceNull(obj.Name2) + '</td><td>' + ReplaceNull(obj.Name3) + '</td><td>'
+ ReplaceNull(obj.Name4) + '</td><td>' + ReplaceNull(obj.Name5) + '</td><td>' + ReplaceNull(obj.Name6) + '</td><td>' + ReplaceNull(obj.Name7) + '</td><td>'
+ ReplaceNull(obj.Name8) + '</td><td>' + ReplaceNull(obj.9) + '</td><td>' + ReplaceNull(obj.10) + '</td><td>' + ReplaceNull(obj.DisPoNumber1) + '</td><td>' + ReplaceNull(obj.DisPoNumber2) + '</td><td><input name=' + ReplaceNull(obj.Name1) + ' id=in' + ReplaceNull(obj.Name2) + ' type="text" size=15 placeholder="Enter Replacement name" value=' + ReplaceNull(obj.New_Name) + '></td></tr>';
tbody.append(row)
});
table.append(tbody);
var dvTable = $("#hello");
dvTable.html("");
dvTable.append(table);
Ajax -
$.ajax({
type: "GET",
url: '',
async: true,
dataType: "json",
contentType: "application/json; charset= UTF-8",
success: function (response) {
populateTable(glResp);
},
error: function (error) {
console.log(error);
alert("Error in the file format!!");
}
});
I have a hidden field with some values, I have to append these values in HTML table.The number of columns in table is fixed.
I have appended successfully,but after first row,it should append data in new row,instead it is appending in the same row.
This is how I am doing
$("#btntbl").click(function () {
debugger
var tabl = $("#testTable");
var vals = $("#txthidden").val();
for (var i = 0; i < vals.split(";").length; i++) {
for (var j = 0; j < vals.split(";")[i].split(",").length; j++) {
tabl.append("<td>" + vals.split(";")[i].split(",")[j] + "</td>");
}
}
});
Also note that some users dont have value of disabled column
JS Fiddle
How can I add new row each time clicking the button?
You need to split twice and create tr for each row:
$("#btntbl").click(function () {
var tabl = $("#testTable"),
vals = $("#txthidden").val(),
rows = vals.split(';'),
columns, i;
for (i = 0; i < rows.length; i++) {
columns = rows[i].split(',');
tabl.append(
'<tr>' +
'<td>' + columns[0] + '</td>' +
'<td>' + columns[1] + '</td>' +
'<td>' + (columns[2] || '') + '</td>' +
'</tr>'
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btntbl" value="Export to table">
<input type="hidden" value="User1,pwd1;User2,pwd2,disabled;User3,pwd3,disabled;User4,pwd4" id="txthidden" />
<table id="testTable" border="2">
<thead valign="top">
<tr>
<th>User</th>
<th>Password</th>
<th>Disabled</th>
</tr>
</thead>
</table>
Just change target by adding a row
Change
var tabl = $("#testTable");
To
var tabl = $('<tr>');
$("#testTable").append( tab1);
Here is how you can do it
var convertToTable = function (val) {
val = val.split(';');
val = val.map(function (v) {
v = v.split(',');
if (v.length === 2) v[v.length] = 'NA';
return '<td>' + v.join('</td><td>') + '</td>';
});
val = '<tr>' + val.join('</tr><tr>') + '</tr>';
return val;
}
and then
tabl.html(convertToTable(vals));
Demo here
jsFiddle demo
$("#btntbl").click(function () {
var parts = $("#txthidden").val().split(";"), i=0;
for (;i<parts.length;) {
var j=0, tr="<tr>", subParts=parts[i++].split(",");
for (;j<3;) tr += "<td>" + (subParts[j++]||"") +"</td>"; // concatenate
$("#testTable").append( tr +"</tr>" ); // Append once
}
});
You forgot about TD tag, just use open tag before TD and close it in the end