How to use javascript AJAX response to create table dynamically - javascript

I am working on javascript.
I have some API calls(Using Ajax) in my code.
There is a button in my UI
on click of this button I am making some API call using AJAX and displaying below HTML UI:
In the table above there are 2 rows. Now if I close this popup and then again click on User Dashboard button it will append those 2 rows again in the table. I dont want to append those rows again.
My code to form table using AJAX response looks like below:
getUserAccountDetailsCallback : function(userid, appid, response){
if(response != "")
{
var res = JSON.parse(response);
var totalNoOfApps = document.getElementById('totalSites');
var totalNoOfSubscriptions = document.getElementById('totalSubscribers');
totalNoOfApps.innerHTML = res.totalNoOfApps;
totalNoOfSubscriptions.innerHTML = res.totalNoOfSubscriptions;
if(res.subscriptionsForCurrentAppId.length > 0){
for(var i = 0; i < res.subscriptionsForCurrentAppId.length; i++){
var td1=document.createElement('td');
td1.style.width = '30';
td1.innerHTML=i+1;
var td2=document.createElement('td');
td2.innerHTML=res.subscriptionsForCurrentAppId[i].gatewayName;
var td3=document.createElement('td');
td3.innerHTML=res.subscriptionsForCurrentAppId[i].priceCurrencyIso;
var td4=document.createElement('td');
td4.innerHTML=res.subscriptionsForCurrentAppId[i].amountPaid;
var date = new Date(res.subscriptionsForCurrentAppId[i].subscribedDate);
date.toString();
var td5=document.createElement('td');
td5.innerHTML=date.getMonth()+1 + '/' +date.getDate() + '/' + date.getFullYear();//res.subscriptionsForCurrentAppId[i].subscribedDate;
var td6=document.createElement('td');
td6.innerHTML=res.subscriptionsForCurrentAppId[i].transactionId;
var td7=document.createElement('td');
td7.innerHTML=res.subscriptionsForCurrentAppId[i].active;
var tr=document.createElement('tr');
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
tr.appendChild(td6);
tr.appendChild(td7);
var table = document.getElementById('tbl');
table.appendChild(tr);
}
}
}
}
Please help. Where I am doing wrong.

add thead and tbody
<table>
<thead><tr><th>#</th><th>Gateway.....</tr></thead>
<tbody id="tBodyId"></tbody>
</table>
remove the content of tbody before appending
like this:
var tBody = document.getElementById("tBodyID");
while (tBody.firstChild) {
tBody.removeChild(tBody.firstChild);
}
if(res.subscriptionsForCurrentAppId.length > 0){

Related

JQuery Header not displaying in Table

I am building a table with JQuery and everything seems to work, except I can't get the header to show up. I'm declaring the header, appending to the table, then appending the column names to the header. The rest of the table displays exactly how I want it to. I didn't think it should matter what order I do this in. What am I doing wrong?
$(document).ready(function(){
if ($('[attr="searchResultsJson"]').length)
{
$('.comment-section').hide();
$('#InboxDetailsDrawer').hide();
$('.approval-outer-wrap').prepend(drawTable());
}
});
function drawTable(){
var table = $('<table id="search-results" />');
var header = $('<thead />');
table.append(header);
header.append = $('<tr><th>First Name</th><th>Last Name</th><th>Date of Birth</th><th>Data Pulse ID</th><th>Laserfiche ID</th></tr>');
var body = $('<tbody />');
table.append(body);
var json = $('[attr="searchResultsJson"] [type="text"]').text();
console.log(json);
var searchResults = JSON.parse(json);
for (var i = 0; i < searchResults.length; i++)
{
body.append('<tr>'+
`<td>${searchResults[i].patientFirstName}</td>` +
`<td>${searchResults[i].patientLastName}</td>` +
`<td>${searchResults[i].patientDateOfBirth}</td>` +
`<td>${searchResults[i].patientDataPulseID}</td>` +
`<td>${searchResults[i].patientLaserFicheID}</td>` +
'</tr>')
}
return table;
}
The append() is a function and you need to pass the content as an argument against append = when appending the header content. Please find the corrected code below.
$(document).ready(drawTable);
function drawTable() {
var table = $('<table id="search-results">');
var header = $('<thead>');
table.append(header);
header.append('<tr><th>First Name</th><th>Last Name</th><th>Date of Birth</th><th>Data Pulse ID</th><th>Laserfiche ID</th></tr>');
var body = $('<tbody>');
table.append(body);
$('body').append(table);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Dynamically update existing table record with jQuery

I'm building an application in which there is a sign-up form. When I click submit, a new table row is dynamically created and the table is saved in local storage. Edit and Delete buttons are appended with the table row. When I click on Edit, data in td having classes name, mail, mob, add should populate name, email, mobile no. and address fields in the sign up form respectively. Furthermore when I submit, the changes should be updated in the same table row whose edit button I had clicked.
But instead of that, a new record is created. I'm attempting to pass the row id to the add function in my code and this is what I have done so far.
function save(){
var taskList = [];
$("#saveTable tbody").find("tr").each(function(){
var task = {};
var currentRow = $(this).closest("tr");
task.name = currentRow.find('.name').text();
task.mail = currentRow.find(".mail").text();
task.mob = currentRow.find(".mob").text();
task.add = currentRow.find(".add").text();
task.Country = currentRow.find(".country").text();
task.State = currentRow.find(".state").text();
taskList.push(task);
});
saveObject("tasks",taskList);
}
function saveObject(recordKey,jsObject){
var objectAsString = JSON.stringify(jsObject);
localStorage.setItem(recordKey,objectAsString);
}
function load(){
var taskList = loadObject("tasks");
for(var index=0; taskList && index<taskList.length; ++index){
this.add(taskList[index]);
}
}
function loadObject(recordKey){
var objectAsString = localStorage.getItem(recordKey);
return JSON.parse(objectAsString);
}
function add(taskObject,index){
if(index){
console.log(index);
var update = $('#saveTable tbody').find('tr').eq(index);
}
var newTR = $("<tr class='child'></tr>");
var newName = $("<td class='name'></td>");
var newMail = $("<td class='mail'></td>");
var newMob = $("<td class='mob'></td>");
var newAdd = $("<td class='add'></td>");
var newCountry = $("<td class='country'></td>");
var newState = $("<td class='state'></td>");
var edit = $("<input class='button_ed' type='submit' value='Edit'/>");
var del = $("<input class='button_del' type='submit' value='Delete'/>");
$(newTR).append($(newName).text(taskObject.name));
$(newTR).append($(newMail).text(taskObject.mail));
$(newTR).append($(newMob).text(taskObject.mob));
$(newTR).append($(newAdd).text(taskObject.add));
$(newTR).append($(newCountry).text(taskObject.Country));
$(newTR).append($(newState).text(taskObject.State));
$(newTR).append($(edit)).append($(del));
$("#saveTable tbody").append($(newTR));
$(edit).on("click",function myEdit(){
event.preventDefault();
if (this.value=="Edit") {
this.value="Save";
var ed = this.closest("tr");
$('#contact_name').val($(ed).children("td.name").text());
$('#contact_email').val($(ed).children("td.mail").text());
$('#contact_mob').val($(ed).children("td.mob").text());
$('#contact_address').val($(ed).children("td.add").text());
$('#contact_name').addClass("valid");
$('#contact_email').addClass("valid");
$('#contact_mob').addClass("valid");
$('#contact_address').addClass("valid");
//collect table row id in variable and pass it to add function
index = ed.rowIndex;
//console.log(index);
save();
}
});
$(del).on("click",function myDel(){
$(this).closest("tr").remove();
save();
});
}

Using javascript Not able to disable textbox.It Immediatly enable after disabled. Can anyone give me solution?

I have One simple registration Form which is developed in C#.Net. This form also contain one Grid view which display data from database.In this,I want to disable Insert button when i select particular raw data. and i had develop this code in jquery. I used below code.
function DoStuff(lnk) {
debugger;
var grid = document.getElementById('GridView1');
var cell, row, rowIndex, cellIndex;
cell = lnk.parentNode;
row = cell.parentNode;
rowIndex = row.rowIndex;
cellIndex = cell.cellIndex;
var rowId = grid.rows[rowIndex].cells[0].textContent;
var rowname = grid.rows[rowIndex].cells[1].textContent;
var rowcontact = grid.rows[rowIndex].cells[2].innerHTML;
var rowaddress = grid.rows[rowIndex].cells[3].innerHTML;
var rowemail = grid.rows[rowIndex].cells[4].innerHTML;
var Id = document.getElementById('txt_Id');
var name = document.getElementById('txt_Name');
var contact = document.getElementById('txt_PhoneNumber');
var address = document.getElementById('txt_Address');
var email = document.getElementById('txt_EmailId');
Id.value = rowId;
name.value = rowname;
contact.value = rowcontact;
address.value = rowaddress;
email.value = rowemail;
document.getElementById('Button1').disabled = true;
};
But when i run that page it becomes disable and immediately enable automatically.....:(
Can anyone give me solution ???
You have to call this function after form is completely loaded.
Use below code to make it that happen if you are using jQuery.
$( document ).ready(function() {
DoStuff(lnk);
});

Editable table cells with App Inventor

I am building an app with App Inventor. I use a Webviewer to load a JavaScript code (see below) that displays, in a table, the content of a database stored in TinyDB.
So basically I have a table that looks like that:
I've tried to make the content of my table editable by adding this at the bottom of my script but without success: my table disappears.
<script>
function myFunction() {
document.getElementById("myTable").contentEditable = true;
}
</script>
Also I've also seen this page. But I can't find way to implement this .js in my App Inventor app.
Any idea how to make this work?
<body>
<div id="myTable"></div>
<script>
// get the table to display from the window.AppInventor object and split at new line
var urlArray = window.AppInventor.getWebViewString().split("\n");
var doc = document;
var fragment = doc.createDocumentFragment();
for(i=0;i<urlArray.length;i++){
var tr = doc.createElement("tr");
// split at comma
var rowArray = urlArray[i].split("|");
for(j=0;j<rowArray.length;j++){
if ( i == 0) { var td = doc.createElement("th"); }
else { var td = doc.createElement("td"); }
td.innerHTML = rowArray[j];
tr.appendChild(td);
fragment.appendChild(tr);
}
}
var table = doc.createElement("table");
table.appendChild(fragment);
doc.getElementById("myTable").appendChild(table);
</script>
</body>

Loop through gridview rows on client-side javascript

I have a gridview with a template field of check boxes.
I have my rows color coded in BLUE color in the gridview based on a database value on page load.
Now I want a button on the page to loop through the gridview and select the the checkbox for the rows that are in BLUE Color without a post back.
any help would be appreciated.
thanks.
Loop through gridview rows on client-side javascript
var GridviewRows = $("#<%=gvbooksdetails.ClientID%> tr").length;
var rowlenght = GridviewRows - 1;
for (var i = 0; i < rowlenght; i++)
{
var Aname = document.getElementById("MainContent_gvbooksdetails_lblgvauthorname_" +[i]+"").innerHTML;
var Bname = document.getElementById("MainContent_gvbooksdetails_lblgvbookname_" +[i]+ "").innerHTML;
var BType = document.getElementById("MainContent_gvbooksdetails_lblgvbooktype_" +[i]+ "").innerHTML;
var Pubilication = document.getElementById("MainContent_gvbooksdetails_lblgvPublisher_" + [i] + "").innerHTML;
var Bid = document.getElementById("MainContent_gvbooksdetails_hiddenid_"+[i]+"").value;
}
Instead of foreach we can use this method.
$('#mygrid tr.blueClass input[type="checkbox"]').each(
function() {
this.checked = true;
});
Assuming mygrid is the name of your gridview, and each blue row has a class called blueClass

Categories

Resources