Easily setting field values with JavaScript - javascript

Wasn't really sure how to ask the question, but my situation is this...
I have a table with one row, which contains a few input boxes. When a user presses the add new, I have managed to add another row to the table. First I make a new variable called oldtable, and then split it at each <tr>.. and save that to the array rows. I use this code:
var newdata="";
for(i=0;i<rows.length;i++)
{
// adds the next row on...
newdata=newdata+rows[i]+"<tr>";
}
newdata=newdata+"MY NEW ROW GOES HERE!";
Then I go on to reset the table innerHTML to the newdata variable.
All works fine, until the user enters data in the first row, and then goes to add data in the second. Then the values on the first row are gone, understandably. Taking into account that the table can theoretically have as many rows as the user wants, how can I go about keeping the values of the first row intact? Is there a way to insert data into the table without reseting what's there?
Thanks.
var olddata = document.getElementById("products_table").innerHTML;
// This splits up each row of it
var rows = olddata.split("<tr>");
// Makes a variable where the new data is going to be stored
var newdata = "";
// This loop is to add back the existing html into the table, it is one short, because we Omit the "add new product" row.
for(i=0;i<rows.length-1;i++)
{
// adds the next row on...
newdata=newdata+rows[i]+"<tr>";
}
// Adds the additional html needed to
newdata=newdata+"my new row goes here!";
// Add newly edited table back in...
document.getElementById("products_table").innerHTML=newdata;

Instead of manipulating HTML in string form (very error prone), you should use the built-in DOM manipulation methods to add new rows to your table. Make sure your table has a TBODY element and give it an ID:
<table id = "product_table">
<tbody id = "product_table_tbody">
<tr>
<td>A Cell</td>
</tr>
</tbody>
</table>
Then, attach an event handler to the Add Row button and do something like this:
function addRow() {
var myTbody = document.getElementById("products_table_tbody");
var myRow = document.createElement("tr");
var myCell = document.createElement("td");
myCell.innerHTML = "My new cell";
myTbody.appendChild(myRow);
myRow.appendChild(myCell);
}

Related

How to pass clicked/selected row data from one table to another table that are placed side by side

I have two tables that are placed side by side and i would to append selected row on the first table to the second tab
i managed to get the data from a selected row and convert it to an array. I tried using the v-bind tag to bind the data values in the second table and its not working
I expect to click a row in a table and that row is added to another table that is just placed on the side of the other table
What I understood from you question is that you are looking for a jquery code that makes the rows from the two tables to move from one table to the other whenever the user clicks on a row in any of the tables.
for example if you click on a row in first table, it moves to the second table and if you click on a row in second table, it moves to the first table.
if it is so, then the jquery code could be:
// identify the two tables with IDs for easier access
var tbl1=$('#table_1_id'), tbl2=$('#table_2_id');
// use tbody selector to make sure that you don't bind this event to table heading rows
$('#table_1_id,#table_2_id').find('tbody tr').on('click', moveRow);
function moveRow() {
// find on which table this row is
var row = $(this);
var table_current = row.closest('table');
// If current table ID equals to first table ID then it means we are in first table
if (table_current.prop('id')==tbl1.prop('id')) {
// Then we move the row to second table
tbl2.find('tbody').append(row);
} else {
// The row was in second table so we move it to first table
tbl1.find('tbody').append(row);
}
return;
}

Getting the row information on click with JQuery

So I'm trying to get the data in my table row on click and create/update another table with the clicked information. The problem is I'm not sure how to pass the data. As of right now I can click on the table rows and get the events started and It looks like my second table is created as well but the information is not passed properly.
I appreciate it if someone can help me by telling me how I'm supposed to pass the information
$(document).on("click", "tr", function(HTMLTableRowElement){ // watch the whole document for when existing (or new) tr elements are clicked
//console.log("table row clicked!");
let tbody = $("#employee-Details tbody");
let fullNameTd= $('<tr>').text(HTMLTableRowElement.FirstName+' '+HTMLTableRowElement.LastName);
let hireDate= $('<tr>').text( moment((HTMLTableRowElement.HireDate)).format('MM/DD/YYYY'));
let fullAddress= $('<tr>').text(HTMLTableRowElement.AddressStreet+' '+HTMLTableRowElement.AddressCity+' '+HTMLTableRowElement.AddressState+' '+HTMLTableRowElement.AddressZip);
let salaryBonus = $('<tr>').text(' $ '+HTMLTableRowElement.SalaryBonus);
// append all table cells to a new row
let row = $('<tr>').append(fullNameTd).append(hireDate).append(fullAddress).append(salaryBonus); // create the row and append // all of the tr elements.
// replace the row on the table body
tbody.replaceWith(row);
In the click callback function you can pass in the event object. You are passing in HTMLTableRowElement and using it as a row element, which is incorrect. You can access the clicked row with $(this)[0], and inside the row you can access the individual cells.
Check out this plunker: link
For example to get the first and last name you need to get the first and second cell's text:
let fullNameTd = $('<tr>').text(thisRow.cells[0].innerText + ' ' + thisRow.cells[1].innerText);
Also the tbody.replaceWith(row); line will only work for the first time, because you are replacing the tbody with a row, so jquery will not find it for the second time. It's better to clear the tbody, and then append the row:
tbody.empty();
tbody.append(row);

Cannot add click to only one table row

When I execute the following to add a click function to the cell at the end of A particular row, jQuery adds the click function to all of the rows. What am I missing here please?
og_rownum happens to equal a number 3, not a string, and the nth-child(8) column does exist in the table.
$("#game_lister_table tr:eq("+og_rownum+"), :nth-child(8)").click(function(e){
alert('here');
e.stopPropagation();
});
Thanks in advance....
It seems like you want to add a listener to only one row on your table. If thats the case just add id="yourID" to the tag that you want to manipulate.
Then in jquery, select it with
$('#yourID').click(function(e){
//code here
});
If you don't know which row needs to be manipulated, and want to choose it programmatically, then try this.
$("#game_lister_table tr").click(function(e){
$(this)...//selects the row that was clicked
})
I used to to this code when choosing specific Cell/ Cells in HTML table Like You
$("#game_lister_table tr:eq("+og_rownum+"), :nth-child(8)").click(function(e){
alert('here');
e.stopPropagation();
});
But I found there is an easy way is to Create Dynamically Id for cell every time you create row or cell you have an Easy way to use JQuery Selector for any (row , cell ,....etc)
var table = document.getElementById("myTable");
var rowIndex =table.rows.length;
var row = table.insertRow();
var cell1 = row.insertCell(0);
cell1.id="whatEver";
cell1.innerHTML = "<input type="text" id="txt'+rowIndex+'" />";
then your action came Next
$('#ID').on('click',function(e){});
Since the closest answer was removed, I'll add this.
Use "#game_lister_table tr:eq("+og_rownum+") td:nth-child(8)" to select the element you described.

How to use Jquery Objects to insert in cells in the midde of a dynamical created Table

The company I work for has a html table that can be designed by the user.
The table is put into JQuery objects by using closest('table')
We allow columns to be added but the one problem we have is the following.
When we try and insert a cell into column into the middle of the table insertbefore or insertafter does not work.
it does not create a td into the middle of the row, therefore as anyone got any idea we can shift the cells to the left by one cell.
The structure of the table is in collection of row objects that has cells array by using the cellIndex.
The table structure is not updated till all cells are added for the column and have been added and adjusted for rowSpan or colSpan.
the code below is how we try and insert at present.
self.newCell '<td data-cmstype="container"><p class="editor-temp">New Cell</p></td>'
var leftSpanedCell = row[cellindex];
var newCell = $(self.newCellHtml);
newCell.insertBefore(leftSpanedCell.td);
The answer is to decrease any span or rowspans and redraw the row table with the objects
I also needed to create my cells properly by creating an object as cell I needed to create an object and then set it to the row array.
var obj = {};
obj.td = $(self.newCellHtml).insertAfter(td);
obj.col = newTD;
obj.length = colSpan
obj.row = cell.row;
thisrow[newTD] = obj

Adding new row on a table tbody by cloning the last row with events attached

I'm trying to clone the last row of a table with input fields that might have events attached, (in this case it's the keyup event). I also change the id's of the input fields to reflect the row where they are, something like:
table[0].field1,table[0].field2...table[1].field1...etc.
The problem is that I can add a row and it gets the events too, and when i write on the new cloned inputs they do start the events. But only on the first row created. If i create a new one, it will render the row with the inputs correctly but not the events. Here's the method:
addRow= function(tableid){
//jquery selector get table tbody with id
var table=jQuery('table[id="'+tableid+'"] >tbody');
//get last row containing input fields with tr class hoverTransparente
var lastRow=jQuery('table[id="'+tableid+'"] > tbody > tr:last');
//make a clone of the row
var clones = lastRow.clone(true); // copy events/children too
//get the input fields from the cloned row
var clonedInPuts=clones.find('input');
//for each input
jQuery(clonedInPuts).each(function (){
//set new input val to empty
jQuery(this).val("");
var inputId=jQuery(this).attr('id');
//table id
var table=inputId.split("[")[0];
//column id
var tableField=inputId.split(".")[1];
var idnumber=inputId.indexOf("[")+1;
//convert to number to make addition for new id index
var number = Number(inputId.charAt(idnumber))+1;
//replace id index with incrementaed value
var newId=inputId.replace(inputId.charAt(idnumber),number);
//change id for new one
jQuery(this).attr('id',newId);
//check if this variable exists/is not undefined
if(window["elements_"+table+"_"+tableField]){
window["elements_"+table+"_"+tableField].push(jQuery(this).get(0));
}
});
clones.appendTo(table);
}
Any ideas? when i try to debug in chrome the event onkeyup from the domtree of the input element is null but if i select using jquery directly and get the .data('events') method it does return an array with the events attached to the input field. Shouldn't the onkeyup return something different from null?
Ok, so the problem is not on this side but on the original method that creates the events in the original inputs of the existing rows. You need to do this:
var selectorStr='input[id^='+table+']&[id$='+tableField+']';
jQuery(document).on('keyup',selectorStr,function(event) {...})
instead of:
var elements=jQuery('input[id^='+table+']&[id$='+tableField+']');
elements.each(function() {
jQuery(this).keyup(function(){...})
});
This will solve the problem of adding new rows to the tablet and the input events actually search for newly added inputs.

Categories