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));
});
}
});
});
});
});
Related
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
}
});
}
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 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
I have the following jquery funcion that's supposed to get a value from a text field:
My Php Code
function asset_status() {
$query = $this->db->query("SELECT count(job_card_no) as job_card_no,number,asset.type,asset.status,asset.id as asset_id FROM asset inner join assgnd_rsces on assgnd_rsces.name = asset.id inner join job_card on job_card.id = assgnd_rsces.job_card_id");
$result = $query->result_array();
echo json_encode($result);
}
ajax request
asset_status_list = '';
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>operations/asset_status",
dataType: "JSON",
success: function (response) {
console.log(response); // it gives following
//job_card_no "2" number "1" status "Active" type "Toilet"
for (i = 0; i < response.length; i++) {
asset_status_list = '<tr><td >' + response[i].job_card_no + '</td><td >' + response[i].number + '</td><td>' + response[i].type + '</td><td ><input type="hidden" name="view_more_id" class="view_more_id' + response[i].id + '" id="view_more_id" value="' + response[i].id + '"/><button id="view_more_link" class="view_more_link' + response[i].id + '"><i class="glyphicon glyphicon-zoom-in "></i>View More</button></td></tr>';
$('#asset_status_tr').append(asset_status_list);
$("#asset_status_tr").on("click", ".view_more_link" + response[i].id, function () {
var asset_id = $(".view_more_id"+response[i].id).val();
alert(asset_id);
});
}
$('#asset_table_status').DataTable({});
},
error: function (response) {
}
});
However when I try it using the above function, I get the following error on click of the button.
TypeError: response[i] is undefined
var asset_id = $(".view_more_id"+response[i].id).val();
How do I solve the above error ?
Yes, you are not getting 'json' from file that's why its length is 0 and its shown you 'undefined'.Please make sure that.
Ok i have some search results from input box. I used keyup to get results. Then tis results send to AJAX, and i want to append it to table. My problem is because i use append i will get more than one table headers if i have more results, on the other side i cant use html() because script use for loop so i will only get one result. Can someone help me to solve this problem. I try something like this...
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);;
$('#result').html('');
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
$('#result').append('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody><tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr> </tbody></table> ' );//dodavanje rezultata u div
}
}
})
}
});
Just create the table once and then append trs in the loop to its tbody
$('#warning').html(response.msg);
if (response.result.length) {
var $table = $('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody></tbody></table>').appendTo($('#result').html(''));
var $tbody = $table.find('tbody');
for (var i = 0; i < response.result.length; i++) //petlja za pristup json
{
$tbody.append('<tr><td>' + response.result[i].id + '</td><td>' + response.result[i].naslov + '</td><td>' + response.result[i].autor + '</td><td>' + response.result[i].cena + '</td><td>' + response.result[i].valuta + '</td></tr> '); //dodavanje rezultata u div
}
} else {
$('#result').html('')
}
Try this :
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);
// Store jQuery objects if used more than once
var $table = $('<table class="page-list">').appendTo($('#result')),
$thead = $('<thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead>').appendTo($table),
$tbody = $('<tbody>').appendTo($table);
innerHTML = '';
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
innerHTML += '<tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr>' );//dodavanje rezultata u div
}
// Append to HTML only once, when you have the full HTML to append
$tbody.append(innerHTML);
}
})
}
});