Dynamically update existing table record with jQuery - javascript

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();
});
}

Related

I want to catch the argument whose checkbox is checked

I want to catch the argument whose checkbox is checked but if my tr is under form then he is giving me the whole tr. Please help me.
Here is my jQuery code:
$('#form').on('submit',function(e){
e.preventDefault();
if($('.checkbox').is(':checked')){
var selector = $(this).closest("tr")//get closest tr
console.log(selector)
//get select valus
var id = selector.attr('data-id');
alert(id);
var package_name = selector.find('.visa_type').val();
var prcs_type_price = selector.find("select[name=processing_type]").val();
var processing_type = selector.find("select[name=processing_type] option:selected").text();
var total = selector.find(".package_price").text(prcs_type_price).val()
var date = selector.find('.travel_date').val();
}
)};
Just run .each over the checked ones
$('#form').on('submit', function(e) {
e.preventDefault();
$('.checkbox:checked',this).each(function() {
const $row = $(this).closest("tr");
const id = $row.id;
const package_name = $row.find('.visa_type').val();
})
You CAN do this .on("input" and have the fields update on any change

Populating a container with one entry per Firebase entry

I'm using Firebase to store users info and I'm wanting to populate divs with each users info so it can be either accepted or deleted (but not deleted from Firebase).
So I wanted it to be structured something like this:
----------------------
Name
Email
Date
----------------------
Name
Email
Date
----------------------
and so on....
What I'm currently getting back is something like this:
What is the proper way to generate a div dependent upon how much data is in Firebase and format the content as specificed?
HTML:
<div>Some entry here
<h4 id="name"></h4>
<h4 id="date"></h4>
<h6 id="email"></h6>
<button id="0" class="remove">Remove</button>
</div>
<div>Another entry here
<button id="1" class="remove">Remove</button>
</div>
Javascript:
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email = child.val().Email;
var name = child.val().Name;
var date = child.val().Scheduled_Date;
date = date.replace('.', '/');
$('#name').append(name);
$('#email').append(email);
$('#date').append(date);
});
});
For each child, you are appending the values to the same HTML elements (i.e. all the names are appended to the h4 element with id "name", all the emails to the one with id "email" and so on).
So it is normal they are displayed on a line (one row).
You have to create a new placeholder for each child (and it's set of values). You can do that with e.g. a table, like:
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email = child.val().Email;
var name = child.val().Name;
var date = child.val().Scheduled_Date;
date = date.replace('.', '/');
// Insert a row in the table at the last row
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell with name value
var newText = document.createTextNode(name); // <-- name value from the child
newCell.appendChild(newText);
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(email); // <-- email value from the child
newCell.appendChild(newText);
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(date); // <-- date value from the child
newCell.appendChild(newText);
});
});
Inspired by How to insert row in HTML table body in Javascript?. See the fiddle in this SO post.
Or you can do it with divs, here is a possible code:.
HTML
<div id="parentDiv"></div>
JavaScript
var element;
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email = child.val().Email;
var name = child.val().Name;
var date = child.val().Scheduled_Date;
date = date.replace('.', '/');
element = document.createElement("div");
element.appendChild(document.createTextNode(name));
document.getElementById('parentDiv').appendChild(element);
element = document.createElement("div");
element.appendChild(document.createTextNode(email));
document.getElementById('parentDiv').appendChild(element);
element = document.createElement("div");
element.appendChild(document.createTextNode(date));
document.getElementById('parentDiv').appendChild(element);
//You could add a specific css class to this div to generate the bottom border
});
});
To be complete, note that you could also use some MVVM javascript frameworks like vue.js, knockout.js as well as angular, react... in order to easily reflect in your HTML DOM the results of queries to your backend (and vice-versa).

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);
});

Need text in input to not display user input once sent

Here is my jQuery, I have it working properly but once my row is added the user input in the inputs are still there and not cleared. How do I fix this?
// Removing menu rows
$('.menu-items').on('click', '.delete', function(){
$(this).closest('.menu-row').remove();
});
// HTML
var MENU_ROW_TEMPLATE = '<div class="menu-row"><span class="item-description">$description</span><div class="control-items"><span class="item-price">$price</span><span class="delete">X</span></div></div>'
// Adding menu rows
$('.menu-category').on('click', 'button', function(){
var $row = $(this).closest('.add-item');
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
var newRowHtml = MENU_ROW_TEMPLATE.replace('$description', name).replace('$price', price);
var $newRow = $(newRowHtml);
var $lastMenuRow = $row.closest('.menu-category').find('.menu-row').last();
$newRow.insertAfter($lastMenuRow);
});
Sorry for my poor explaining skills.
Clear the name and price after you get the values...
...
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
$row.find('input').first().val('');
$row.find('input').last().val('');
...

How to use javascript AJAX response to create table dynamically

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){

Categories

Resources