How to get each table row and its respective inputs (checkbox, text, select) into an array to store in localstorage? I've complete most of the code, the part I need to build is the ???? part. Thanks.
This is the javascript code:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
$('#btnSave').on('click', function(e) {
e.preventDefault();
var id = $(this).attr("data-id");
var mykey = 'set'+id;
// here just to check whether 'set'+id exist or not, no validation performed
if(localStorage.getItem(mykey)==null){
console.log('key not found');
} else {
console.log('key found');
}
// Due to there will be one or more rows,
// need to loop the rows and get the inputs within
// and store them in localstorage
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
console.log(checkbox);
console.log(itemcode);
console.log(amount);
console.log(reference);
});
localStorage.setItem(mykey, ????);
});
This is the input button if you wonder how i dynamically generate the table row
<input type="button" value="Add row" onClick="addRow('dyn_table')" />
Create an array of objects.
var array = [];
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
array.push({
checkbox: checkbox,
itemcode: itemcode,
amount: amount,
reference: reference
});
console.log(checkbox);
console.log(itemcode);
console.log(amount);
console.log(reference);
});
localStorage.setItem(mykey, JSON.stringify(array));
I didn't know if I understood your problem but this is working ?
var my_table = [] // Create an array for the table
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
// For each row, create a item on the array, containing all important data for the row
my_table.push({checkbox, itemcode ,amount, reference})
});
console.log("My table :", my_table)
localStorage.setItem(mykey, JSON.stringify(my_table));
If you don't want to save each col like: {checkbox: true, itemcode: 'foo', ...} but have an ordered array instead, you can replace the new line by:
my_table.push([checkbox, itemcode ,amount, reference])
Related
why i cannot select the first data and the second data when i tested using console.log
This is the table:
var ref = firebase.database().ref("recommendations");
ref.on("value", function(snapshot) {
// console.log(snapshot.val());
var recommendations = snapshot.val();
var keys = Object.keys(recommendations);
console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var title = recommendations[k].title;
var link = recommendations[k].link;
var presenter = recommendations[k].presenter;
// document.getElementById('title').innerHTML = title;
// document.getElementById('presenter').innerHTML = presenter;
// document.getElementById('link').innerHTML = link;
var table = document.getElementById("data");
var tr = document.createElement('tr');
var td1 = tr.appendChild(document.createElement('td'));
var td2= tr.appendChild(document.createElement('td'));
var td3 = tr.appendChild(document.createElement('td'));
var tdEdit = tr.appendChild(document.createElement('td'));
td1.innerHTML = title;
td2.innerHTML = presenter;
td3.innerHTML = link;
tdEdit.innerHTML = "<button id='"+k+"' class='btn btn-default edit'>Edit</button>";
table.appendChild(tr);
}
$(document).ready(function() {
$(".edit").on("click", function(){
console.log(k);
})
});
});
The issue is that you log k which is a reference to inside the loop. So the loop go's key0 key1 key2 and stays key2 because thats the last value of k.
Use something like:
$(document).ready(function() {
$(".edit").on("click", function(){
// From the button perspective this references the Native element.
console.log(this.id); // or $(this).attr("id")
})
});
I have a dynamically created HTML table. In each row is a dropdown, I need to add options to the dropdown. My code, however, will only add values to the first row.
Here is how I am creating the table and trying to add the options.
$.post(
'dataform.php',
{ functionname: JSON.stringify('operation'), args:part},
function(response) {
result = JSON.parse(response);
block = []
for (var item in result){
var objectItem = result[item];
var opnum = objectItem.opnum;
var opdesc = objectItem.opdesc;
var wc = objectItem.wc;
var sel = document.createElement("select");
sel.type = "select";
sel.id = "sel";
sel.value = wc;
var activity = objectItem.activity;
var machine = objectItem.machine;
var direct_labor = objectItem.direct_labor;
block.push(opnum);
block.push(opdesc);
block.push(wc);
block.push(sel);
block.push(activity);
block.push(machine);
block.push(direct_labor);
ops.push(block);
block = [];
}
for (var i = 0; i < ops.length; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.appendChild(document.createElement('td'));
tr.cells[0].appendChild(document.createTextNode(ops[i][0]));
tr.cells[1].appendChild(document.createTextNode(ops[i][1]));
tr.cells[2].appendChild(ops[i][3]);
tr.cells[3].appendChild(document.createTextNode(ops[i][4]));
tr.cells[4].appendChild(document.createTextNode(ops[i][5]));
tr.cells[5].appendChild(document.createTextNode(ops[i][6]));
table.appendChild(tr);
}
tablearea.appendChild(table);
},
)
$.post(
'dataform.php',
{functionname: JSON.stringify('wc')},
function(response) {
result = JSON.parse(response);
block = []
for (var item in result){
var objectItem = result[item];
var wrkc = objectItem.wc
var act_key = objectItem.activity;
debugger;
$.each($('#sel').append($("<option></option>").html(wrkc)));
}
}
)
})
I have tried having the the options appended each time the cell is created and I had the same results.
Any help would be greatly appreciated.
Thanks!
('#sel') the ID selector uses document.getElementById() internally, which can return only an element. So it will add to just one. Use a class if you want to append it to each element that contains the said class.
http://jsfiddle.net/waH5S/6/
function add_row_retail() {
$(document).ready(function () {
var table = document.getElementById("Retail");
var row = table.insertRow(-1);
var row_id = $('#Retail').val('tr[id]:last');
console.log(row_id);
var cell_init = row.insertCell(-1);
cell_init.innerHTML = "blank";
});
}
I am trying to get the id of the table row(<tr>) before the added row, and then add 1 to this, with proper parseint(...). Then doing the same with the cell (<td>) next, so that every cell has a unique id for each table. I can't seem to find the row's id.
HERE IS THE "CORRECT" CODE FOR MY QUESTION
function add_row_retail() {
var table = document.getElementById("Retail");
// Row id
var row_id = $('#Retail tr:last').attr('id');
var row = table.insertRow(-1);
var next_row_id = "tr_" + (1+parseInt(row_id.match(/\d+/)[0],10));
$(row).attr('id', next_row_id);
for (var i = 0; i < 8; i++) {
var cell_id = $('#Retail td:last').attr('id');
console.log(cell_id);
var next_cell_id = "td_" + (1+parseInt(cell_id.match(/\d+/)[0],10)); console.log(next_cell_id);
var cell = row.insertCell(-1);
$(cell).attr('id', next_cell_id);
$(cell).innerHTML = "blank";
}
}
Rather than $('#Retail').val('tr[id]:last'); I think you want:
var row_id = $('#Retail tr:last').attr('id')
This selector finds the last tr under the #Retail element, and returns its id attribute.
jQuery last selector: http://api.jquery.com/last-selector/
Next problem: IDs cannot start with numbers. Rename your IDs like "tr_1", "tr_2", etc.
Next problem: To extract the numbers from a string:
"tr_123".match(/\d+/)[0]; // returns 123.
Add 1 to it:
var next_id = "tr_" + (1+parseInt("tr_123".match(/\d+/)[0],10));
Then, set your new id.
var row = table.insertRow(-1);
...
$(row).attr('id', next_id);
I have try to get cell data on gridComplte event but I am not able to getting a value of cell
so,please suggest me how to get that?
gridComplete: function ()
{
var ids = jQuery("#list").jqGrid('getDataIDs');
alert(ids);
for(var i=1;i<=ids.length;i++)
{
var rowId = ids[i];
// var rowData = jQuery('#list').jqGrid ('getRowData', rowId);
var cont = jQuery('#list').getCell(rowId, 'SYS'); //SYS is my colNames
var val = $(cont).val();
alert(val);
}
},
In your code above, variable "cont" should have the value of 'SYS' column.
Remove the line
var val = $(cont).val();
Here is the corrected code:
gridComplete: function ()
{
var ids = jQuery("#list").jqGrid('getDataIDs');
alert(ids);
for(var i=1;i<=ids.length;i++)
{
var rowId = ids[i];
// var rowData = jQuery('#list').jqGrid ('getRowData', rowId);
var cont = jQuery('#list').getCell(rowId, 'SYS'); //SYS is my colNames
alert(cont);
}
},
I want to delete a row from a table, I am using Javascript.
I am dynamically creating table rows and in the last cell I have delete button so how to make it delete the row?
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
this is the function for creating my table rows
function addItem()
{
document.getElementById('add').onclick=function()
{
var myTable = document.getElementById('tbody');
var newRow = document.createElement('tr');
//var element1 = document.createElement("input");
//element1.type = "checkbox";
//newRow.appendChild(element1);
var newData1 = document.createElement('td');
newData1.innerHTML = document.getElementById('desc').value;
var newData2 = document.createElement('td');
newData2.innerHTML = document.getElementById('taskPriority').value;
var newData3 = document.createElement('td');
newData3.innerHTML = document.getElementById('taskDue').value;
myTable.appendChild(newRow);
newRow.appendChild(newData1);
newRow.appendChild(newData2);
newRow.appendChild(newData3);
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
}
}
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
try this code here is fiddle
alternatively try
//delete the table row
$(document).on('click', '#del', function(){
$(this).parents('tr').remove();
});
}); //del is the id of the delete block
one pure javascript approach
function deleteRowUI(btndel) {
var table=document.getElementById('filterTableBody');
if (typeof(btndel) == "object") {
p=btndel.parentNode.parentNode;
p.parentNode.removeChild(p);
var oTable = document.getElementById('filterTableBody');
//gets rows of table
var rowLength = oTable.rows.length;
for (var i = 1; i < rowLength; i++){
var oCells = oTable.rows.item(i).cells;
//gets cells of current row
var cellLength = oCells.length-1;
for(var j = 0; j < cellLength; j++){
oCells.item(j).innerHTML = "";
break;
}
break;
}
} else {
return false;
}
}
if you want to temporary hidden it you can do:
this.parentNode.style.display='none';
in mind that the exclusion button is in a td.
But if you want to really delete it from the html and the database:
you need to make the same as above and a extra call to a function of php/plsqlwathever to delete from de db, i recommend using ajax to call it.
http://www.w3schools.com/ajax/default.asp
uses jQuery remove method to do it.
By the id attribute :
$("#id here").remove();
By the class attribute :
$(".class name here").remove();
I hope I've helped a little...