I need to access to the data of a html cell,but before that ,I need to store the id of my array (details[i].id) in a cell. I tried with a hidden, but I get an empty cell when I show the table and that's not what I want, what I want is something like the DataKeyNames in ASP.net, that gives us the chance to store the id without necessarily showing it.
This is the code I use to show my array (details) in a html table:
function showTable()
{
if (details.length>0){
for (var i=0; i<details.length;i++)
{
var tbl = document.getElementById('myTable');
var newRow = tbl.insertRow(tbl.rows.length);
var cell1 = newRow.insertCell(0);
cell1.textAlign='center';
cell1.innerHTML=details[i].price;
var cell2 = newRow.insertCell(1);
cell2.textAlign='center';
cell2.innerHTML=details[i].description;
var cell3 = newRow.insertCell(2);
cell3.textAlign='center';
cell3.innerHTML='<img src="images/delete.png" width="14" height="14" alt="Delete" onclick="removeDetail(this)"/>'
}
}
}
And finally in the removeDetail function is where I need to get the cell value, assuming I somehow put the id there.
function removeDetail(r)
{
var node = r.parentNode;
while( node && node.tagName !== 'TR' ) {
node = node.parentNode;
}
var i=node.rowIndex;
document.getElementById('myTable').deleteRow(i);
//here's where I need to get the id and, if posible the other values ( price, description) too.
}
Hope you can help me out.
First step: store the index as custom attribute of your element:
cell3.innerHTML='<img src="images/delete.png" width="14" height="14" alt="Delete" onclick="removeDetail(this)" details_index="' + i + '" />'
Second step: store the row as part of the global array:
details[i].row = newRow;
Final step: In the removeDetail function read the index and you have all you need:
function removeDetail(r)
{
var item = details[parseInt(r.getAttribute("details_index"), 10)];
item.row.style.display = "none";
alert("price: " + item.price + ", description: " + item.description);
}
Try below code :
function checkSequence()
{
var oTable = document.getElementById('tableID');
var rowLength = oTable.rows.length;
var count=0;
for (i = 0; i<rowLength-1; i++){
var cellVal = document.getElementById('tableID:'+i).value;
}
}
Related
I need to add images to a given table. I have the following code:
HTML:
<div class="container" id="game"></div>
Javascript
function table() {
var i,
x,
domRow,
domCol,
rows = $("#rows").val(),
colums = $("#columns").val(),
table = $('<table>'),
cellId = 0;
table.empty();
for(i = 0; i < rows; i++) {
domRow = $('<tr/>');
for(x = 0; x < colums; x++) {
domCol = $('<td/>',{
'id': "cell-" + cellId++,
'class': "cell",
'text': 'cell',
'data-row': i,
'data-col': x
});
domRow.append(domCol);
}
table.append(domRow);
}
return table;
}
Now I want do add images to each data cell from another function.
Example:
function images() {
var game = $("game");
// TODO the images need to be added too
game.append(table())
}
An image with the name 0.png needs to be added to the data cell with the id="cell-0" and so on... (1.png to id="cell-1")
How could I do this?
The jQuery append method can take a function that returns the HTML string to append. And within that function this refers to the element. So you can just find all the td elements in your table and append the right image to each one:
function images() {
var game = $("game");
var tableEl = table();
tableEl.find('td').append(function () {
// `this` is the <td> element jQuery is currently appending to
var num = this.id.split('-')[1];
return '<img src="' + num + '.png" />';
});
game.append(tableEl)
}
Try setting window.myTable or similar to the output of table(), and then edit the table by acessing it from window.myTable.
For adding the images, what I would instead recommend is just inserting:
var img = $('<img>');
img.attr('src', parseInt(cellId) + ".png");
img.appendTo(domCol);
Right before domRow.append(domCol); (I did not test this).
Here is a simple code to add your images in each cell that its id correspond.
$('[id^=cell-]').each(function() {
var curCell = $(this);
curCell.html('<img src="' + curCell.attr('id').substring(5) + '.png">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr><td id="cell-0">1</td><td id="cell-1">2</td></tr>
</table>
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 a table which contains two rows.
<tr id="row1"><td>first row</td></tr>
<tr id="row2"><td>second row</td></tr>
I need to insert few rows between row1 and row2 using java script.
I can achieve this by using java script create element. But I wish to add new rows using string html content.
for example :
"<tr><td>This row is placed between first and second</td></tr>".insertAfter(first row Id);
is there way like this to add rows in between?
var newRow = document.createElement("tr");
newRow.innerHTML = "<td>This row is placed... etc.</td>";
var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2);
Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore
Use jQuery. There is a Function insertAfter();
$("#row1").insertAfter("your html");
http://jquery.com/
var button = document.getElementById('insert');
var table = document.getElementById('table');
button.onclick = function() {
var position=Math.round(table.rows.length / 2);
var row = table.insertRow(position);
row.innerHTML = '<td>This row is placed between '+position+' and '+(parseInt(position)+1)+'</td>';
}
**after that if u can use like that u can increment ur row id also:**
var rowId = '#' + tableId + ' tr';
var k = 0;
$(rowId).each(function () {
var ObjInput = $(this).find('input[type=text],input[type=radio],input[type=checkbox],textarea,select,input[type=img],input[type=hidden],input[type=button],img');
if (ObjInput != null) {
for (var j = 0; j < ObjInput.length; j++) {
var inputId = $(ObjInput[j]).attr('id');
inputId = inputId.replace(/_[0-9]{1,2}/g, '_' + k);
$(ObjInput[j]).attr('id', inputId);
$(ObjInput[j]).attr('name', inputId);
}
k++;
}
});
I am using local storage to save an object. I am having troubles than using this object to populate a table. Right now the object is showing up as an array in the third column. How can I use the json array to fill column 1, column 2 and column 3 with the value, key and image from the object.
$(document).on('click', '[data-toggle=add]', function() {
var latlng = $(this).data('latlng');
var address = $(this).data('address');
var image = $(this).data('image');
var key = $(this).data('id');
var testObject = {
'latlng' : latlng,
'address' : address,
'image' : image
};
localStorage.setItem(key, JSON.stringify(testObject));
updateTable();
});
function updateTable() {
var tbody = document.getElementById("output");
while(tbody.getElementsByTagName("tr").length > 0) {
tbody.deleteRow(0);
}
var row;
if(localStorage.length == 0) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.colSpan = "4";
cell.innerHTML = "Nothing to Show";
}
for(var i = 0; i < localStorage.length; ++i) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.innerHTML = i;
cell = row.insertCell(1);
cell.innerHTML = localStorage.key(i)
cell = row.insertCell(2);
cell.innerHTML = localStorage.getItem(localStorage.key(i));
cell = row.insertCell(3);
cell.innerHTML = '<button class="btn btn-danger btn-sm" onclick="deleteItem(\'' + localStorage.key(i) + '\');"><i class="fa fa-trash-o"></i> Delete</button>';
}
}
You haven't posted all your markup but I believe this is your problem:
You are not retreiving the localStorage correctly. You are saving a stringified version of a JSON object and then you are trying to access it directly as an object.
Instead, you need to retrieve the localstorage item and parse it back to a JSON object, then iterate through it or access its properties as an object.
Replace:
cell.innerHTML = localStorage.key(i);
With:
json = JSON.parse(localStorage.key(i));
cell.innerHTML = json.latlng;// or json.address or json.image;
Hope this helps!
I'm developing an android app with phonegap. I'm making an HTML table with some that with a for loop from localStorage. I need, for each row, to store the index i of the for to use it for retrieving an item from localStorage that has the name like the index. I have some code but the variable that i defined for that effect gets overwritten by the loop (of course). Here's the code:
<script language="javascript">
if(len != 0) {
var table = document.getElementById('hor-minimalist-b'); // get the table element
var tableBody = table.childNodes[1]; // get the table body
var tableHead = table.childNodes[0]; // get the table head
var thead = document.createElement('th');
var row2 = document.createElement('tr'); // create a new row
var headText = document.createTextNode('Dados');
thead.scope = "col";
thead.appendChild(headText);
row2.appendChild(thead);
tableHead.appendChild(row2);
for (var i=0; i<len; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var a = document.createElement('a');
var cellText = document.createTextNode(localStorage.getItem('key' + i));
var xyz = "key" + i;
a.href = "alterar.html";
a.onclick = function() { doLocalStorage(xyz) };
a.appendChild(cellText);
cell.appendChild(a); // append input to the new cell
row.appendChild(cell); // append the new cell to the new row
tableBody.appendChild(row); // append the row to table body
}}
</script>
</table>
Maybe i'm not explaining myself too well. If you need any more info please ask. Thanks in advance. Eva
try to put the key name in to a closure:
function wrapper(i) {
return function() {
doLocalStorage("key" + i)
}}
a.onclick = wrapper(i);
Not sure if I got your question right, but if you want to bind usage of a variable asynchronously when doing for loop then you should wrap it in a closure:
for(i = 1, c = arr.length; i < c; i++){
(function(i){
// i wont change inside this closure so bound events will retain i
$('#id'+i).click(function(){
alert(i); // Will alert the corresponding i
})
})(i);
}