Save data from an HTML table - javascript

I am working with MVC and I am creating a dynamic table as data from # Html.TextBoxFor is added that I have in my view, and all good so far
My question is: Any way to save my table that I create with a JS function?
Searching the web I found some examples but so far nothing works for me
My Table
<table id="mytable" class="table table-bordered table-hover ">
<tr bgcolor="#90A8D0">
<th>Proyecto</th>
<th>Cuenta</th>
<th>Sub Cuenta</th>
<th>Beneficiario</th>
<th>Tipo de Pago</th>
<th>Pago en el proyecto</th>
<th>Pago Por México</th>
<th>Tarjeta Usuario</th>
<th>Total de Remesa</th>
<th>Obersvaciones</th>
<th>Eliminar</th>
</tr>
</table>
So I create my dynamic table:
$(document).ready(function() {
$('#adicionar').click(function () {
debugger;
var Proyecto = $("#ProyectoID option:selected").text();
var Recurso = $("#RecursoID option:selected").text();
var SubRecurso = $("#SubRecursoID option:selected").text();
var Beneficiario = document.getElementById("Beneficiario").value;
var TipoPago = $("#TipoPagoID option:selected").text();
var PagoProyecto = document.getElementById("PagoProyecto").value;
var PagoMexico = document.getElementById("PagoMexico").value;
var TarjetaUsuario = document.getElementById("TarjetaUsuario").value;
var TotalRemesa = parseInt(PagoProyecto) + parseInt(PagoMexico) + parseInt(TarjetaUsuario);
var ObervacionesCuenta = document.getElementById("ObervacionesCuenta").value;
var i = 1; //contador para asignar id al boton que borrara la fila
var fila = '<tr id="row' + i + '"><td>' + Proyecto + '</td><td>' + Recurso + '</td><td>' + SubRecurso + '</td><td>' + Beneficiario + '</td><td>' + TipoPago + '</td><td>' + PagoProyecto + '</td><td>' + PagoMexico + '</td><td>' + TarjetaUsuario + '</td><td>' + TotalRemesa + '</td><td>' + ObervacionesCuenta + '</td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">Quitar</button></td></tr>'; //esto seria lo que contendria la fila
i++;
$('#mytable tr:first').after(fila);
$("#adicionados").text(""); //esta instruccion limpia el div adicioandos para que no se vayan acumulando
var nFilas = $("#mytable tr").length;
$("#adicionados").append(nFilas - 1);
//le resto 1 para no contar la fila del header
document.getElementById("Recurso").value ="";
document.getElementById("SubRecurso").value = "";
document.getElementById("Proyecto").value = "";
document.getElementById("Proyecto").focus();
});
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
//cuando da click obtenemos el id del boton
$('#row' + button_id + '').remove(); //borra la fila
//limpia el para que vuelva a contar las filas de la tabla
$("#adicionados").text("");
var nFilas = $("#mytable tr").length;
$("#adicionados").append(nFilas - 1);
});
});
This is an example I found on the web:
$(function () {
debugger;
$('#mytable').each(function () {
var cuotaNo= $(this).find('td').eq(0).html();
var interes = $(this).find('td').eq(1).html();
var abonoCapital = $(this).find('td').eq(2).html();
var valorCuota = $(this).find('td').eq(3).html();
var saldoCapital = $(this).find('td').eq(4).html();
$.ajax({
async: false,
type: "POST",
url: "../Guardardatos",
data:"cuotaNo="+cuotaNo+"&interes="+interes+"&abonoCapital="+abonoCapital+"&valorCuota="+valorCuota+"&saldoCapital="+saldoCapital,
data: {valores:valores},
success: function(data) { if(data!="");}
});
});
});
As this last example is what I am trying to save the data that is created in my table

In this example, create TableView, TableRowView, and TableCellView classes. Each class returns an object with an element property and render* method. TableView.element uses the table provided in your example. TableRowView.element and TableCellView.element both create new elements.
After the data from the form (not shown in your example) is POSTED and the success callback is executed: first, create a new instance of TableView; second, create a new instance of TableRowView; third, create new instances of TableCellView for each data property, then render the property value inside of it.
To ensure that the correct order of data elements is rendered, use columnOrder to define the table cell names, the iterate over them in the onSuccess callback. Each iteration, use the column name to access the corresponding data property.
const columnOrder = [
'proyecto',
'cuenta',
'subCuenta',
'beneficiario',
'tipoPago',
'pagoProyecto',
'pagoMexico',
'tarjetaUsuario',
'totalRemesa',
'obersvaciones',
'elminar',
]
const TableView = () => {
let table = document.getElementByID('myTable')
return {
element: table,
renderTableRow: (element) => {
this.element.appendChild(element)
return this
}
}
}
const TableRowView = () => {
let tr = document.createElement('tr')
return {
element: tr,
renderTableCell: (element) => {
this.element.appendChild(element)
return this
},
}
}
const TableCellView = () => {
let td = document.createElement('tr')
return {
element: td,
render: (value) => {
this.element.innerHTML = value
return this
},
}
}
const onSuccess = (event) => {
let data = event.data
/*
data
-----
{
'proyecto': ??,
'cuenta': ??,
'subCuenta': ??,
'beneficiario': ??,
'tipoPago': ??,
'pagoProyecto': ??,
'pagoMexico': ??,
'tarjetaUsuario': ??,
'totalRemesa': ??,
'obersvaciones': ??,
'elminar': ??,
}
*/
let table = new TableView()
let row = new TableRow()
columnOrder.forEach((columnName) => {
let cell = new TableCellView()
let cellData = data[columnName]
cell.render(cellData)
row.renderTableCell(cell.element)
table.renderTableRow(row.element)
})
}
$.ajax({
...,
success: onSuccess,
})

Related

Remove() function doesnt work in firebase for web

This is the js file. What im trying to do is create an onclick delete function when clicked on a particular row in html page. So far i can get the child key(nesting) but somehow the delete function throws error i.e career-delete.html:1 Uncaught ReferenceError: MCu9V4ypS is not defined
at HTMLButtonElement.onclick (career-delete.html:1).
userImagesRef1.once("value", function(snapshot) {
var val1, val2, val3;
var ParentKey = snapshot.key;
console.log("PK"+ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
var childKey = snap.key;
console.log("CK" + childKey);
var Vacancy = snap.child("VacancyNumber").val();
console.log("VacancyNumber" + Vacancy);
// var NoticeNumber = snap.child("Service").val();
// var NameofWork = snap.child("Title").val();
snap.child('pictures').forEach(function(openPicturesSnap){
console.log("KEY LINKS: " + openPicturesSnap.key);
// var i = 0;
if(openPicturesSnap.key == 0){
val1 = openPicturesSnap.val();
// console.log("LINKS1111::::" + val1 );
}
if(openPicturesSnap.key == 1){
val2 = openPicturesSnap.val();
}
if(openPicturesSnap.key == 3){
val1 = openPicturesSnap.val();
}
})
var Service = String(snap.child("Service").val());
// console.log(Service)
var ts = snap.child("timestamp").val();
// console.log("TS:" + ts);
var Title = String(snap.child("Title").val());
// console.log(Title)
let Numberofposts = String(snap.child("NumberofPosts").val());
// console.log(Numberofposts);
var SNo = "";
var State = snap.child("Status").val();
var IssueDate = snap.child("IssueDate").val();
var ClosingDate = snap.child("ClosingDate").val();
var Remarks = String(snap.child("Remarks").val());
$("#tableBody").append("<tr><td>"+ SNo +"</td><td><a href = '" + val1+ "'>" +Vacancy+"</a></td>"+ "<td><a href = '" +val2 + "'>" +Service+"</a></td><td>" + Title + "</td><td>"+Numberofposts+"</td><td>" + IssueDate + "</td><td>"+ClosingDate + "</td> <td>" + State+"<td><a href = '" +val3 + "'>" +Remarks+"</a>"+ "</td><td>"+'<button type="button" onClick=Delete('+childKey+'); class="btn delete">X</button>'+"</td></tr>" );
})
})
function Delete(key){
var feedRef = firebase.database().ref("user-images").child(key);
feedRef.remove()
.then(function(){
console.log("Remove succeeded.")
alert("Added");
// console.log(key.val());
})
.catch(function(error){
console.log("Remove Failed!"+error.message)
});
}
});
You can delete nodes by using the following alternative:
feedRef.set(null);
https://firebase.google.com/docs/database/web/read-and-write#delete_data
You need to add some double quotes as follows:
<button type="button" onclick="Delete('" +childKey+ "');" class="btn delete">X</button>

How not to re-write all of those values all over the Function?

As you can see I have this function:
var review = function() {
$('a[name=review_button]').live("click", function (e) {
e.preventDefault();
/*
* #array of reservations
* #all of the fields
*/
var $tr_options = '';
var reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
reservations[i] = $(selected).text();
});
var amount = $('input[name=amount-price]').val();
var currency_value = $('input[name=currency-value]').val();
var currency_name = $('.currency_appendto option:selected').html();
var actual_amount = $('input[name=actual-amount]').val();
var actual_remaining = $('input[name=actual-remaining]').val();
var funds_arrival_date = $('input[name=funds-arrival]').val();
var paid_to = $('.paidto option:selected').html();
var checkbox = $('.multi-transaction:checked').map(function () {
return this.value
}).get();
var options = troptions(reservations, amount, currency_name, currency_value, actual_amount, actual_remaining, funds_arrival_date, paid_to);
$.each(options, function (k, v) {
$tr_options += '<tr>' + '<td>' + k + '</td>' + '<td>' + v + '</td>' + '</tr>';
}); //one line creating trs awesome
var appendto = (
'<table class="table table-striped mb-none">' + '<thead>' +
'<tr>' + '<th>Information</th>' + '<th>Values</th>' + '</tr>' +
'</thead>' +
'<tbody>' + $tr_options + '</tbody>' +
'</table>'
);
$('[name=review-information]').html(appendto);
});
$('button[name=submit-transaction]').live("click", function (e) {
e.preventDefault();
$.ajax({
url: '/transactions/submit',
type: 'POST',
data: {
amount: $('input[name=amount-price]').val(),
currency_value: $('input[name=currency-value]').val(),
currency_name: $('.currency_appendto option:selected').html(),
actual_amount: $('input[name=actual-amount]').val(),
actual_remaining: $('input[name=actual-remaining]').val(),
funds_arrival_date: $('input[name=funds-arrival]').val(),
paid_to: $('.paidto option:selected').html(),
},
success: function (data) {
console.log(data);
}
});
});
}
review();
$(".date-mask").inputmask("d/m/y",{ "placeholder": "dd/mm/yyyy" });
$(".amount-czk").inputmask('integer', { rightAlign: false });
});
Where i have all of those values:
var reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
reservations[i] = $(selected).text();
});
var amount = $('input[name=amount-price]').val();
var currency_value = $('input[name=currency-value]').val();
var currency_name = $('.currency_appendto option:selected').html();
var actual_amount = $('input[name=actual-amount]').val();
var actual_remaining = $('input[name=actual-remaining]').val();
var funds_arrival_date = $('input[name=funds-arrival]').val();
var paid_to = $('.paidto option:selected').html();
And i need to reuse them in multiple areas of the app, however i don't want to re-write those elements all of the time. Writing those values outside the review function returns the .val(); of unidentified. as those values always change .. How can i make a function that will give me back access to all of those values upon call?
Just return them as properties of an Object
function getValues() {
var o = {};
o.reservations = [];
$('#custom-headers option:selected').each(function (i, selected) {
o.reservations[i] = $(selected).text();
});
o.amount = $('input[name=amount-price]').val();
o.currency_value = $('input[name=currency-value]').val();
o.currency_name = $('.currency_appendto option:selected').html();
o.actual_amount = $('input[name=actual-amount]').val();
o.actual_remaining = $('input[name=actual-remaining]').val();
o.funds_arrival_date = $('input[name=funds-arrival]').val();
o.paid_to = $('.paidto option:selected').html();
return o;
}
Then access as
var values = getValues();
values.actual_amount; // foo

How to get the data from dynamically table

I have a dynamically table I need to get the date from it any place in the script.....
the table
$('#update_panel').html('Loading Date....');
$.ajax({
url: '/Home/GetCountries',
type: 'GET',
datatype: 'Json',
success: function (data) {
if (data.length > 0) {
var $data = $('<table></table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$data.append(header);
$.each(data, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<a href='/home/Save/" + row.CountryId + "' class='popup'>Edit</a> | <a href='/home/Delete/" + row.CountryId + "' class='popup'>Delete</a>"));
$data.append($row);
});
$('#update_panel').html($data);
}
I tried it but it didn't work
$("#mytable tr").click(function () {
var countryId = $(this).find('td').eq(1).text().trim();
alert(countryId);
});
How to reach the table in the Dom?
Thanks in Advance
$.ajax({
url: '/Home/GetCountries',
type: 'GET',
datatype: 'Json',
success: function (data)
{
if (data.length > 0)
{
// HERE I HAVE APPLIED 'id' ATTRIBUTE TO TABLE
var $data = $('<table id="mytable"></table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$data.append(header);
$.each(data, function (i, row)
{
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<a href='/home/Save/" + row.CountryId + "' class='popup'>Edit</a> | <a href='/home/Delete/" + row.CountryId + "' class='popup'>Delete</a>"));
$data.append($row);
});
$('#update_panel').html($data);
}
}
});
//USE 'on' EVENT WHEN YOU WANT TO TRIGGER EVENT ON DYNAMIC DOM
$("#update_panel").on("click", "#mytable tr", function ()
{
// IT WILL SELECT ALL 'td' CHILDREN OF CLICKED 'tr' ELEMENT.
// THEN WE USED .first() SO IT WILL SELECT ONLY FIRST 'td' ELEMENT
var countryId = $.trim($(this).children("td").first().text());
alert(countryId);
});
Here is some observations and a possible solution:
Your dynamic table is missing the ID (mytable)
Once it is added your code should work fine. See the code below,
var data = [];
var row1 = {};
row1.CountryId = "100";
row1.CountryName = "USA";
data.push(row1);
var row2 = {};
row2.CountryId = "101";
row2.CountryName = "Germany";
data.push(row2);
if (data.length > 0) {
var $data = $('<table id="mytable"></table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$data.append(header);
$.each(data, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<a href='/home/Save/" + row.CountryId + "' class='popup'>Edit</a> | <a href='/home/Delete/" + row.CountryId + "' class='popup'>Delete</a>"));
$data.append($row);
});
$('#update_panel').html($data);
}
$("#mytable tr").click(function () {
var countryId = $(this).find('td').eq(0).text().trim();
alert(countryId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="update_panel"></div>
Seems like your table did't have an id #mytable. Change $("#mytable tr").click(function () { into :
$('#update_panel').on('click','.table tr',function () {...});
Or simply adding id #mytable into table
$('<table id="myTable"></table>')
And register it handler using .on like so :
$('#update_panel').on('click','#mytable tr',function () {...});

General link to get all details of each imdb top 250 movie?

for a school assignment I chose to load all of the movies from top250 list dynamically with Ajax to a singlepage and from that page everytime I choose a movie from the list, a popover shows up with the details of that movie. What I wanted to know is how to get a general link for all movies to get the details for each movie on that list because I'm stuck with "The Shawshanks Redemption"-link. Here's the code
$(document).ready(function () {
$.ajax({
url: "crosscall/crosscall.php",
data: {
'url': 'http://www.imdb.com/chart/top?ref_=nv_ch_250_4' //Site van IMDB die de Top 250 toont.
},
type: "POST",
success: function (data) {
var $data = $(data);
var titel = $('.titleColumn');
var nummer = 0;
var imageURL = 'http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_SX214_AL_.jpg';
var imageID = 'image';
var image = $('.posterColumn td a img').attr('src');
$(document.body).append('<img id="' + imageID + '">');
$.ajax({
url: 'hotlink.php?url=' + imageURL,
success: function (base64data) {
$('#' + imageID).attr('src', 'data:image/png;base64,' + base64data);
}
});
$data.find('.titleColumn').each(function () {
var titel2 = $(this).find('a').text();
var datum = $(this).find('span[name=rd]').text();
var plaats = $(this).find('span[name=ir]').text();
if (titel2.length > 10) titel2 = titel2.substring(0, 38);
if (nummer < 250) {
$('.container').append('<div class="imgurstyle"><div class="titel"><h1>' + plaats + ' ' + titel2 + ' ' + datum + ' </h1></div><img src="' + imageURL + image + '" alt="image"></div>');
}
});
//Als men op een film klikt, zal de popover tevoorschijn komen.
$("a.popLink").click(function (event) {
//voorkomt dat het link waarop men zal klikken herlaadt.
event.preventDefault();
showPopover1();
});
var popoverBG;
var popover;
//functie popover maken zoals bij de oefeningen die we hadden behandeld tijdens WC.
function showPopover1() {
//maak popoverBG
popoverBG = document.createElement('div');
popoverBG.className = 'popoverBG';
document.body.appendChild(popoverBG);
//maak popover
popover = document.createElement('div');
popover.className = 'popover';
$.ajax({
url: "crosscall/crosscall.php",
data: {
'url': 'http://www.imdb.com/title/tt0111161/?ref_=chttp_tt_1' //Details van elk filmpagina ophalen.
},
type: "POST",
success: function (data) {
//gegevens ophalen in popover steken
var $data = $(data);
var jaartal = $('.infobar');
var nummer = 0;
$data.find('.infobar').each(function () {
var titel = $(this).parent().find('h1 span[itemprop=name]').text();
var jaartal2 = $(this).find('.nobr').text();
var rating = $(this).find('div .titlePageSprite star-box-giga-star').appendTo('li');
console.log($(this).find('.titlePageSprite star-box-giga-star'));
var genre = $(this).find('.itemprop').text();
var regisseur = $(this).parent().find('div[itemprop="director"] span ').text();
var schrijver = $(this).parent().find('div[itemprop="creator"] span').text();
var acteurs = $(this).parent().find('div[itemprop="actors"] span').text();
var meerAct = $(this).parent().find('.see-more inline nobr a[itemprop="url"]').text();
var plot = $(this).parent().find('p[itemprop="description"]').text();
var tijdsduur = $(this).find('time').text();
if (nummer < 250) {
popover.innerHTML = '<header><h2>' + titel + '</h2></header><ul><li><img src="images/shawshank%20redemption.jpg" alt="n1"></li><li>Release:' + jaartal2 + '</li><li>User ratings:' + rating + '</li><li>Genre: ' + genre + '</li><li>Duur: ' + tijdsduur + '</li><li>Regisseur: ' + regisseur + '</li><li>Schrijvers:' + schrijver + '</li><li>Acteurs: ' + acteurs + ' ' + meerAct + '</li><li>' + plot + '</li></ul><p>Meer info klik Hier<p>Close</p>';
}
});
}
});
document.body.appendChild(popover);
//voeg click toe aan popoverBG
popoverBG.onclick = removePopover;
function removePopover() {
document.body.removeChild(popoverBG);
document.body.removeChild(popover);
};
};
}
});
});

shorthand javascript ? for making vars?

Is there a bether way to do this ?
i try serval things, but this one is the only that works for me
var naam = $("#resvNaam").val();
var aantal = $("#resvAantal").val();
var uur = $("#resvUur").val();
var datum = $("#resvDatum").val();
var telefoon = $("#resvTelefoon").val();
var opmerking = $("#resvOpmerking").val();
var alles = "?naam=" + naam + "&aantal=" + aantal + "&uur=" + uur + "&datum=" + datum + "&telefoon=" + telefoon + "&opmerking=" + opmerking;
You can put all the ids in an array, then use map:
var ids = [
'naam',
'aantal',
...
]
var ucfirst = function(x) {
return x[0].toUpperCase() + x.slice(1)
}
var alles = '?'+ ids
.map(function(id) {
var value = encodeURIComponent($('#resv'+ ucfirst(id)).val())
return id +'='+ value
})
.join('&')
I would suggest using the same id or name for the field and the query, so it is easier to manipulate, and write less code.
As suggested in the comments, if you use names it would be easier to serialize the form with jQuery using http://api.jquery.com/serialize/

Categories