removing items from an Array when clicking delete icon in html row - javascript

I have a bit of a problem. I'm trying to add,remove and edit items in an array of objects, showing its content in a html table,but without form submission. So far I've managed to add items ( thanks to David Calhoun ), but now I facing a new issue, since I don't know how to get the row index (when I click the delete image) ,so that I can delete that row. Is there any way to achieve this?
here's my code
<script>
var table = [];
function addDetail()
{
table.push({
price: document.getElementById('price').value,
description: document.getElementById('descripcion').value
});
showRow(table.length-1);
resetEntries();
}
function resetEntries()
{
document.getElementById('price').value='';
document.getElementById('descripcion').value='';
document.getElementById('price').focus();
}
function showRow(i)
{
if (table.length>0){
var tbl = document.getElementById('tabla_estilo');
var newRow = tbl.insertRow(tbl.rows.length);
var cell1 = newRow.insertCell(0);
cell1.textAlign='center';
cell1.innerHTML='<img src="images/edit.png" width="14" height="14" alt="Edit"/>'
var cell2 = newRow.insertCell(1);
cell2.textAlign='center';
cell2.innerHTML='<img src="images/delete.png" width="14" height="14" alt="Delete"/>'
var cell3 = newRow.insertCell(2);
cell3.textAlign='center';
cell3.innerHTML=table[i].price;
var cell4 = newRow.insertCell(3);
cell4.textAlign='center';
cell4.innerHTML=table[i].description;
}
}
And here's how my form looks

From the onclick handler for the delete button, you can traverse up to its <tr> and then get that row's rowIndex property.
So in the onclick:
var node = this.parentNode;
while( node && node.tagName !== 'TR' ) {
node = node.parentNode;
}
var index = node.rowIndex;
So when you're setting up your row cells, you can add a handler:
var cell2 = newRow.insertCell(1);
cell2.textAlign='center';
cell2.innerHTML='<img src="images/delete.png" width="14" height="14" alt="Delete"/>'
cell2.firstChild.onclick = function() {
var node = this.parentNode;
while( node && node.tagName !== 'TR' ) {
node = node.parentNode;
}
var index = node.rowIndex;
alert('index');
return false;
}
This creates a new function for each row. It would be better to reference a named function instead.

with JQuery use any of these selector
$('table tr').each(function(i, v) { alert((i+1) + ' row') });
$('table tr:nth-child(i)').hide();
OR
<a href="#" class="delete" onclick="$(this).parent().parent().hide()">

When you create a new row in the table use a custom attribute in to store the index of the element in the array:
<tr position='0'><td></td><td></t></tr>
<tr position='1'><td></td><td></t></tr>
<tr position='2'><td></td><td></t></tr>
<tr position='3'><td></td><td></t></tr>
Alternatively, if your rows are always in the same order as the elements in the array you may check how many previous siblings there are before this row.
I would use the first approach as it will still work if you reorder the rows in the table.
Make sure that if you delete the row you then recalculate row position attributes.

Related

Create row in html table which does not have id and class

I would like to create one additional row in HTML Table which is very common and can be done if we have id or class available of that table.
But in my case I have one page which contains many forms and tables.
But in all those I have one form which contains only one element i.e table and I would like to create one more row and move few columns from 1st row to newly created row.
For this I have created simple HTML page.Please find below code and help me to achieve my output.
<h:form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</h:form>
Here Ia m getting output like
Item Info Description Product Keywords Documents Image Video
But I want to achieve something like below:
Item Info Description Product Keywords
NEW CELL1 Documents Image Video
means I would like to remove few columns from existing row and I would like to add it in newly created row.
For this I have written Javascript like:
<script type="text/javascript">
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.elements[0];
var tr = document.createElement("tr");
tr.id="row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
var col5 = document.getElementById("col5");
tr.appendChild(col5);
var col6 = document.getElementById("col6");
tr.appendChild(col6);
var col7 = document.getElementById("col7");
tr.appendChild(col7);
}
</script>
Here, My problem is this entire form will be generated automatically so I can't give the Id for the table and with this script it is not identifying my table when I am giving form.elemets[0];
I want to find table element so that I can create row in that table.
You can find the table by doing this:
Get one of the elements in a table row, and get the parent node until you've got the table. In this case you could do document.getElementById('col1').parentNode.parentNode
And just to ease things,
You can insert this string '</tr><tr>' in a row, after a table cell, to easily create a new row.
This should be better than document.getElementsByTagName('table'), because if you have lots of tables which are far away, it will take more time to find your table's index in that array.
Use getElementsByTagName to get the table from within your form, which has an ID
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.getElementsByTagName("table")[0];
var tr = document.createElement("tr");
tr.id = "row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
/*Your original code produces duplicate IDs which is a BAD thing*/
var col5 = document.getElementById("col5");
/*Update new Id*/
col5.id += "_new";
tr.appendChild(col5);
var col6 = document.getElementById("col6");
/*Update new Id*/
col6.id += "_new";
tr.appendChild(col6);
var col7 = document.getElementById("col7");
/*Update new Id*/
col7.id += "_new";
tr.appendChild(col7);
}
<form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</form>
You also have a mismatch of column numbers, with the code provided you originally have 7 columns and only insert 4, this will produce inconsistent results, make sure to use the colspan attribute as needed.
You should be able to use JavaScript's querySelector method to select the table data you want to remove from the document.
Something like var rowToDeleteOrAddTo = document.querySelector("#myForm > table > tr > td"); should help you get there. You'll need to lookup CSS Selectors to get the specific selectors you need. You may need to use the textContent property once you have a node to make sure you are deleting the right one.

Jquery .find doesn't look into the father element

I was trying to clone and change all the ids of a line in a table following the answer https://stackoverflow.com/a/2977114/327247
but the code below doesn't change the first id: the row id.
The javascript is
var $clone = $("#RowPly-R1-P1");
$clone.find('[id]').each(function() {
var $th = $(this);
var newID = $th.attr('id').replace(/-P\d+$/,
function(str) { return "-P"+i; });
console.log(newID);
$th.attr('id', newID);
});
console.log($clone);
$clone.appendTo($tableToModfiy);
$clone.after($("RowPly-R1-P1"));
while the html is
<tbody id="tblPlayers">
<tr id="RowPly-R1-P1">
<td>1</td>
<td>
<div class="input-group">
............
</div>
</td>
</tr>
</tbody>
All the ids internal to the row are successfully changed.I cannot understand why find doesnt change the first ID.
Because .find() will find all the descendant elements of the clone element, not the clone element itself so the ID of the clone element is not updated.
$clone.find('[id]').addBack()
You can also try a attr('id', callback) format like
var $clone = $("#RowPly-R1-P1");
$clone.find('[id]').addBack().attr('id', function(i, id) {
return id.replace(/-P\d+$/,
function(str) {
return "-P" + i;
});
});

td's in table creating with jquery without html

Here is my jsfiddle work. I have some issues with generating table without any html. I have one json object that i need to itterate and to put keys and values in table like:
<tr> <td> key </td> <td> key </td> ... </tr>
<tr> <td> val </td> <td> val </td> ... </tr>
I tried first to generate the table like this one, but next i wanted to use jquery version of creating td's and tr's, but the all keys and values were appended in only one td and actually this is not what i want.
You have to loop through keys the first time to set the head of table, after that make the rows inside each and append every one to the table to make the body of your table, check example code bellow :
$.ajax({
type : "POST",
dataType : "json",
url : '/echo/json/',
data : { json: JSON.stringify( jsonData ) },
success : function(data){
var jsn = $(data.markers);
//First time append table head
if(!header)
{
var row = $('<tr></tr>');
for(key in jsn[0])
{
row.append('<th>'+key+'</th>');
}
table.append(row);
header = true;
}
for ( var i = 0; i < jsn.length ; i++){
var row = $('<tr></tr>');
$.each(jsn[i], function(key,val)
{
row.append('<td>'+val+'</td>');
});
table.append(row);
}
}
});
Take a look at Working fiddle.
Hope this helps.
The issue was in the scope of the col and row variables. You must reassign them in the loop, or redeclare.
Here is the updated jsfiddle. By the way there is no need to use for loop. In jQuery it is enough to use the $.each function on the object.
From here you can see how to create table structure and replace the key and val with the actual data you need.
You need to create new row object in each for iteration:
for (var mrksIndex = 0, mrksLength = jsn.length; mrksIndex <= mrksLength; ++mrksIndex) {
row = $("<tr/>");
$.each(jsn[mrksIndex], function (key, val) {
col = $("<td/>");
col.append(key);
row.append(col);
table.append(row);
});
}
Demo: https://jsfiddle.net/6dw2u8uz/15/

Handling the table from a html form with javascript

<table id="production">
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
<tr>
<th>Product Name</th>
<td></td>
<td>elementsdefined</td>
</tr>
</table>
Product Name:
Product Quanitity:
Add
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table = document.getElementById("production");
var rows = table.rows;
var cell1 = rows[0].insertCell(-1);
var cell2 = rows[1].insertCell(-1);
cell1.innerHTML = prdn;
cell2.innerHTML = prdq;
}
I need someone help me understand how I can insert data in separate column in database; suppose I have a table of three rows and three columns, columns are created by using td tags, now in the first and last columns elements are predefined and so any data should insert in the second column of the table after clicking the button. because the code above is inserting the data in raw cells by default.
i am adding the fiddle here
http://jsfiddle.net/3e7rh/2/
As you can see here, you need to add in the last - 1 column.
http://jsfiddle.net/3e7rh/8/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].insertCell(rows[0].cells.length - 1);
var cell2=rows[1].insertCell(rows[1].cells.length - 1);
cell1.innerHTML=prdn;
cell2.innerHTML=prdq;
}
Update:
http://jsfiddle.net/3e7rh/10/
function updateForm() {
var prdn = document.getElementById("prodname").value;
var prdq = document.getElementById("prodquantity").value;
var table=document.getElementById("production");
var rows=table.rows;
var cell1=rows[0].cells[1].textContent=prdn;
var cell2=rows[1].cells[1].textContent=prdq;
}
Get the table. Iterate over all rows and fill in the first td (Because you are using th as the first one)
var table = document.getElementById("production")
rows = table.getElementsByTagName("tr");
for(var i=0;i<rows.length;i++)
{
columns = rows[i].getElementsByTagName("td");
columns[0].textContent="text"; //First Td second column in your case
}
Jsfiddle:http://jsfiddle.net/7xs6v/1/
I am assuming you want to fill the same text in every first td(second column). If you want individual then you can use the index specificallyinstead of iterating over for loop

Possible to append html before and after template?

Is it possible to append html before and after a JQuery.tmpl?
I would like to insert a nested table in
<table id="accTable">
<tr class="row" id="12345">
</tr>
<!-- New row to be inserted here -->
</table>
so I have done
var dat = [];
$.each(result, function(key, value){
dat.push({
FROM: this.date,
ID: key,
});
});
var markup = "<tr> <td>${ID}</td> <td>${FROM}</td> </tr>";
$.template("actTemplate", markup);
$('#'+id).tmpl("actTemplate", dat).after('#'+id);
But somehow I need to append <tr><td><table> and prepend </table></td></tr>.
I have thought about adding that HTML to the existing, but it should happen in a button press, so until it is pressed would it look wrong. So I guess the append and prepend have to happen when the template is inserted...?
Any suggestions on how to solve this?
Update
In this jsFiffle will a row be added/removed when "Details" is clicked. This is the row that I would like to replace.
http://jsfiddle.net/littlesandra88/hhMM6/
You can make it this way:
EDITED
var wrapper = $( '<tr id="details"><td><table></table></td></tr>' );
var wrapperTable = wrapper.find( 'table' );
$.tmpl ("actTemplate", dat ).appendTo( wrapperTable );
wrapper.insertAfter( '#'+id );
I would solve it this way:
//create your wrapping elements
var wrapping_elements = $('<tr><td><table class="new-table"/></td></tr>');
$('#'+id).after(wrapping_elements);
//insert your table data
var template_data = $('#'+id).tmpl("actTemplate", dat);
$('table.new-table').append(template_data);

Categories