I am dynamically creating a table using JavaScript/jQuery/html from an Ajax call. The first time the table loads it displays correctly formatted. However, when I do a refresh/reload the formatting of the table is not correct. I have included Promise to try and fix it as per How to Promisify an Ajax Call
Correct on first load:
After reload:
The abbreviated code is:
$('#refreshTableBtn').click(function(){
//Re-display the exercise table
exerciseFirstColumnDetails()
.then((numExeDetails) => {
console.log(numExeDetails)
loadExerciseDetails(numExeDetails)
})
.catch((error) => {
console.log()
})
});
function exerciseFirstColumnDetails() {
//Get Patient Exercise Details
$('#exerciseTable tr').empty();
var numExeDetails = 0;
//Get the Patient's exercise headers
return new Promise((resolve, reject) => {
$.ajax({
url: "PatientExerciseHeadersListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
reject();
})
.done(function(responseJson1a) {
dataType: "json";
if (Object.keys(responseJson1a)[0] == "empty") {
$('#ajaxGetUserServletResponse4').text('No Exercise details.');
}else {
//Create first table column
//Loop through the Execise details
//Populate the variable number of exercise variables and keep count.
$.each(responseJson1a, function() {
numExeDetails++;
var html = "";
html += "<tr id='ExerciseDetail"+numExeDetails+"' name='" + this.edeId + "'>";
html += "<td class='bgColourWhiteBold sticky-col'>"+ this.edeType + " - " + this.edeUnit + "</td>"
html += "</tr>"
$(html).insertBefore($("#InsertSet"));
});
}
resolve(numExeDetails);
});
});
};
function loadExerciseDetails(numExeDetails) {
$.ajax({
url: "PatientExerciseDetailsListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
viewFrom : $("#viewFromDate").val(),
viewTo : $("#viewToDate").val(),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
})
.done(function(responseJson1a) {
dataType: "json";
$('#ajaxGetUserServletResponse4').text('');
if (Object.keys(responseJson1a)[0] == "empty") {
//Display an empty table for data entry
//Check if the date range includes today's date.
if (moment($("#viewFromDate").val(), 'DD/MM/YYYY').isAfter(moment())
|| moment($("#viewToDate").val(), 'DD/MM/YYYY').isBefore(moment())){
$('#ajaxGetUserServletResponse4').text('No Patient exercises in this date range.');
}else {
var today = moment(new Date()).format("DD/MM/YYYY");
var todayDay = moment(new Date()).format('ddd')
//If the date range includes todays date then display an empty table for data entry
$("<th class='h1Colour'>Set 1</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 2</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 3</th>").appendTo($("#tableHeadersSet"));
//Create three sets for each Exercise Detail
for(let i = 1; i <= numExeDetails; i++) {
var ExerciseDetail = "ExerciseDetail" + i;
alert(ExerciseDetail);
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='1' value='' size='4'></td>").appendTo($('#'+ExerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='2' value='' size='4'></td>").appendTo($('#'+ExerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='3' value='' size='4'></td>").appendTo($('#'+ExerciseDetail));
}
}
}else{
//Display existing sets
}
});
}
HTML:
<table id='exerciseTable'>
<tr id="tableHeadersSet">
<!-- Place for Set row -->
</tr>
<tbody id="tableBody">
<!-- Add each of the Exercise Details -->
<tr id="InsertSet">
<!-- Place for Insert Set button -->
</tr>
</tbody>
</table>
The answer is to move the population of the first column to where I do the input lines.
$('#refreshTableBtn').click(function(){
//Re-display the exercise table
exerciseFirstColumnDetails()
.then(({numExeDetails, exercises}) => {
console.log({numExeDetails, exercises})
loadExerciseDetails({numExeDetails, exercises})
})
.catch((error) => {
console.log(error + " Error in exerciseOverview.js - call 'loadExerciseDetails' function");
})
});
function exerciseFirstColumnDetails() {
//Get Patient Exercise Details
$('#exerciseTable tr').empty();
var numExeDetails = 0;
var exercises = [];
//Get the Patient's exercise headers
return new Promise((resolve, reject) => {
$.ajax({
url: "PatientExerciseHeadersListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
reject();
})
.done(function(responseJson1a) {
dataType: "json";
if (Object.keys(responseJson1a)[0] == "empty") {
$('#ajaxGetUserServletResponse4').text('No Exercise details.');
}else {
// $("#chartDisp").show();
//Create first table column
$("<th class='h2Colour sticky-col' colspan='1'>Week</th>").appendTo($("#tableHeadersWeek"));
$("<th class='bgColourWhite sticky-col' colspan='1'>Date</th>").appendTo($("#tableHeadersDate"));
$("<th class='bgColourWhite sticky-col' colspan='1'>Day</th>").appendTo($("#tableHeadersDay"));
$("<th colspan='1' class='tdNoBorder sticky-col'></th>").appendTo($("#tableHeadersSpace1"));
$("<th class='tdNoBorder sticky-col'></th>").appendTo($("#tableHeadersSet"));
//Loop through the Execise details
//Populate the variable number of exercise variables and keep count.
$.each(responseJson1a, function() {
//Pass 'exercises' to the next funtion
exercises[numExeDetails] = this.edeType + " - " + this.edeUnit;
numExeDetails++;
var html = "";
html += "<tr id='ExerciseDetail"+numExeDetails+"' name='" + this.edeId + "'>";
// html += "<td class='bgColourWhiteBold sticky-col'>"+ this.edeType + " - " + this.edeUnit + "</td>"
html += "</tr>"
$(html).insertBefore($("#InsertSet"));
});
$("<td class='tdNoBorder sticky-col' colspan='1'></td>").appendTo($("#InsertSet"));
}
resolve({numExeDetails, exercises});
});
});
};
function loadExerciseDetails({numExeDetails, exercises}) {
$.ajax({
url: "PatientExerciseDetailsListView",
data : {
ssAccRole : sessionStorage.getItem('ssAccRole'),
ssAccID : sessionStorage.getItem('ssAccID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
ssPatExeID : sessionStorage.getItem('ssPatExeID'),
viewFrom : $("#viewFromDate").val(),
viewTo : $("#viewToDate").val(),
},
type: "POST",
cache: false,
//Loading spinner
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
})
.fail (function(jqXHR, textStatus, errorThrown) {
$('#ajaxGetUserServletResponse4').text('Error getting Exercise details.');
})
.done(function(responseJson1a) {
dataType: "json";
$('#ajaxGetUserServletResponse4').text('');
if (Object.keys(responseJson1a)[0] == "empty") {
//Check if the date range includes today's date.
if (moment($("#viewFromDate").val(), 'DD/MM/YYYY').isAfter(moment())
|| moment($("#viewToDate").val(), 'DD/MM/YYYY').isBefore(moment())){
$('#ajaxGetUserServletResponse4').text('No Patient exercises in this date range.');
}else {
var today = moment(new Date()).format("DD/MM/YYYY");
var todayDay = moment(new Date()).format('ddd')
//If the date range includes todays date then display an empty table for data entry
$("<th class='h2Colour' colspan='3'>1</th>").appendTo($("#tableHeadersWeek"));
$("<th class='h1Colour' colspan='3'>" + today + "</th>").appendTo($("#tableHeadersDate"));
$("<th class='h1Colour' colspan='3'>" + todayDay +"</th>").appendTo($("#tableHeadersDay"));
$("<th colspan='3' class='tdNoBorder'></th>").appendTo($("#tableHeadersSpace1"));
$("<th class='h1Colour'>Set 1</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 2</th>").appendTo($("#tableHeadersSet"));
$("<th class='h1Colour'>Set 3</th>").appendTo($("#tableHeadersSet"));
//Create three sets for each Exercise Detail
var exercisesIdx = 0;
for(let i = 1; i <= numExeDetails; i++) {
var exerciseDetail = "ExerciseDetail" + i;
$("<td class='bgColourWhiteBold sticky-col'>"+ exercises[exercisesIdx] +"</td>").appendTo($('#'+exerciseDetail));
exercisesIdx++;
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='1' value='' size='4'></td>").appendTo($('#'+exerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='2' value='' size='4'></td>").appendTo($('#'+exerciseDetail));
$("<td class='bgColourWhiteBold sticky-col exeSet'><input type='text' name='exeSet' data-set='3' value='' size='4'></td>").appendTo($('#'+exerciseDetail));
}
$("<td class='tdNoBorder sticky-col' colspan='3'><input type='button' name='addSetBtn' class='btn btn-sm h2Colour' style='width:100%' value='Add Set'></td>").appendTo($("#InsertSet"));
}
}else{
//Display existing sets
}
});
}
Related
I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<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 data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>
When onclick the status update then only corresponding row should be refresh . before that i written the drop down onchange function based on that only table row is display.
cs.html:
<section class="card ">
<div class="card-block">
<h5 class="with-border m-t-lg">View Module List</h5>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
<label class="form-label" for="exampleInput">Domain Name</label>
#Html.DropDownList("DomainID", null, "--- Select Domain Name ---", new { #class = "select2-arrow" })
</fieldset>
</div>
</div>
<br />
<div class="table-responsive" id="findValue" style="display:none;">
<table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
<thead>
<tr>
<th>S#</th>
<th>Module Name</th>
<th>Url</th>
<th>Roles</th>
<th>Action</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</section>
Dropdown based on view tables code:
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
}
else {
item.ModuleName = item.ModuleName
}
var Status = '';
if (item.Status == "Y") {
Status = '<img src="/img/Active.png" height="22" width="42"/>'
} else {
Status = '<img src="/img/InActive.png" height="22" width="42"/>'
}
var rows = "<tr>"
+ "<td>" + (i + 1) + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + ' ' + Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
Update status Code
<script>
$(document).ready(function () {
$("#example tbody").on('click', '.user-status', function () {
var getId = $(this).data('id');
var status = $(this).attr('data-status');
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateStatusModule")',
dataType: 'json',
data: { ModuleID: getId },
success: function (data) {
if (data.success) {
alert(data.message);
$("#example tbody").load("/Account/UpdateStatusModule");
}
},
error: function (ex) {
alert('Failed to retrieve Sub Categories : ' + ex);
}
});
});
});
</script>
i written the drop down onchange function based on that only table row is display. When onclick the status update then only corresponding row should be refresh onchange no value should not be change
#region Update Status
[Authorize]
[HttpPost]
public ActionResult UpdateStatusModule(int ModuleID)
{
try
{
int refID = Convert.ToInt32(Session["RefID"]);
int typeID = Convert.ToInt32(Session["ComTypeID"]);
if (ModelState.IsValid && refID > 0)
{
userType type = new userType();
type.UpdateStatusModule(ModuleID);
}
return Json(new { success = true, message = "updated successfully" }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
#endregion
If you append html after the initialization it can't work.
You need to register events on document(without $(document).ready)
$(document).on("change","#DomainID", function () {
alert("domain changed");
}).on('click', '.user-status', function () {
alert("clicked");
});
For async POST:
$.post("MyUrl",{myId: myId},function(data){
do wathever
}).fail(function(x,y,z){
alert("ops");
});
More simple
I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.
<script type="text/javascript">
$(document).ready(function () {
Get();
setInterval(function () {
Get() // this will run after every 5 seconds
}, 5000);
});
function Get() {
$.ajax({
type: "POST",
url: "../adminpage/noti.ashx",
data: {},
dataType: "json",
success: function (response) {
$.each(response, function (index, itemData) {
var tr = "<tr>" +
"<td>" + itemData.msg + "</td>" +
"<td>" + itemData.dt + "</td>" +
"</tr>";
$("#testTable").find("tbody").append(tr);
});
BindTable();
}
});
}
function BindTable() {
try {
$('#testTable thead th').each(function (i) {
var title = $('#testTable thead th').eq($(this).index()).text();
if (title != "") {
$(this).html('<div style="width:40%;text-align:center;white-space:nowrap">' + title + '</div>');
}
});
}
catch (e) { }
}
</script>
<table id="testTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="m-list-timeline__text" style="width:70%">msg</th>
<th class="m-list-timeline__time" style="width:30%">dt</th>
</tr>
</thead>
<tbody></tbody>
</table>
Try clearing all <tr>nodes from your tbody before you append your results:
success: function (response) {
$("#testTable").find("tbody").empty(); //clear all the content from tbody here.
$.each(response, function (index, itemData) {
/*do stuff*/
$("#testTable").find("tbody").append(tr);
});
BindTable();
}
$('#myTable').empty()
try to remove the content of the table before the ajax call
then fill the data
<script type="text/javascript">
$(document).ready(function () {
Get();
setInterval(function () {
Get() // this will run after every 5 seconds
}, 5000);
});
function Get() {
$.ajax({
type: "POST",
url: "../adminpage/noti.ashx",
data: {},
dataType: "json",
success: function (response) {
// Check if response data is not empty
if (response) {
// Empty previous data
$("#testTable").empty();
// Iterate data for each row
$.each(response, function (index, itemData) {
var tr = "<tr>" +
"<td>" + itemData.msg + "</td>" +
"<td>" + itemData.dt + "</td>" +
"</tr>";
$("#testTable").find("tbody").append(tr);
});
BindTable();
}
}
});
}
I make calculations in the rows of the table. But I have some problems. Let's look at the picture below.
It was supposed to be 26.8. Every time I click on the last row I get the data on the line.
I forgot to add the codes yesterday. sorry
<script type="text/javascript">
$(function () {
$(document).ready(function () {
$(".AddRow").click(function () {
var id = $(this).attr("data-id");
var row = $('#deger tr:last');
$.ajax({
async: true,
url: '/Home/Ekle/' + id,
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (besin) {
//I create the rows of the table
$("#deger tr:last").before("<tr><td style='height:30px;line-height:30px'>" + besin.BesinAd +
"</td><td style='height:30px;line-height:30px'>" + besin.KHDeger + "x" + besin.KHGram +
"</td><td style='height:30px;line-height:30px' class='hKh'>" + besin.KHDeger +
"</td><td style='height:30px;line-height:30px' class='hGr'>" + besin.KHGram +
"</td><td style='height:30px;line-height:30px'><input type='text' class='form-control input-xs txtHesap'></input></td><td style='height:30px;line-height:30px'><button class='btn btn-success btn-xs sil'>Sil</button></td></tr>");
$(".txtHesap").focus();
/*Actions to be performed when a value is entered in the textbox
Where only the last added line gets its value. That's my problem.*/
$("#deger").on('input', '.txtHesap', function () {
var toplam = 0;
var khgr = besin.KHGram; //Values from the controller
var kh = besin.KHDeger; //Values from the controller
$("#deger .txtHesap").each(function () {
var gr = $(this).val();
if ($.isNumeric(gr)) {
toplam += parseFloat((gr * kh) / khgr);
}
});
$("#toplam").html(toplam.toFixed(2));
});
}
});
});
});
});
I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle