Dynamically appending a row by cloning an existing row? - javascript

I have a row in a table and that row is not displayed as css style is set to display:none .
HTML table:
<table class="myTable">
<tr class="prototype">
........
</tr>
</table>
CSS code:
.myTable .prototype{display:none;}
Now i have to clone the same row and add some data to it and append the row to the table as below: i have below jquery code:
var master = $(this).parents("table.myTable");
var prot = master.find(".prototype").clone();
prot.attr("class", "");
prot.find("#attributeValue").attr("value", "ABC");
prot.find("#contactFirstName").attr("value", "XYZ");
jQuery('table.myTable tr:last').before(prot);
But the row won'ttbe added to the table. Please help me.
Thanks!

If you run the code in the onLoad event, change the first line to var master = $(this).find("table.myTable"); or var master = $("table.myTable");
Use prot.removeClass(); instead of prot.attr("class", "");
Ids have to be unique, if elements in your prototype-row have an id you get invalid HTML.
Use $().val('ABC') instead of $().attr('value', 'ABC')
If it still doesn't work, please show more code (maybe a jsfiddle).

var master = $(this).parents("table.myTable");
var prot = master.find("tr.prototype").clone();
prot.removeClass('prototype');
prot.find("#attributeValue").val("ABC");
prot.find("#contactFirstName").val("XYZ");
master.append(prot);
prot.show();

Related

How do I align new table rows added using JS with existing table rows?

The table rows I added are the top 2 (MAT235 and CSC263). If it helps, I can also post the HTML code of the bottom 2 rows and of the top 2 rows.
This is how I added table rows/data:
var tableRef = document.getElementsByClassName('section academic-history xs-block-table')[0].getElementsByTagName('tbody')[1];
var newRow = tableRef.insertRow(1);
var newCell = newRow.insertCell(0);
newCell.innerHTML = 'MAT235Y1'
and this is what the existing rows' HTML looks like
<tr data-ng-repeat="course in session.courses" class="courses">
<td>STA257H1</td>
<td>Probability and Stat I</td>
<td class="course-weight">0.50</td>
</tr>
And this is the new rows' HTML generated by my JS code above.
<tr>
<td>MAT235Y1</td>
<td>Calculus</td>
<td>1.00</td>
</tr>
EDIT: #wOxxOm's comment fixed it for me.
By the request of #isherwood, I am providing an answer I received from #wOxxOm.
The solution is to copy the class name attribute (newRow.className = 'courses') for the new rows.

Append child can`t add more than 1 child node

var data={
1:"dasf",
2:"jlla",
3:"jalf"
};
(function () {
var table=document.createElement("table");
var tr=document.createElement("tr");
for(var i in data){
tr.innerText=data[i];
(function(){
table.appendChild(tr);
console.log("in"+tr.innerText)
})();
console.log("out"+table);
}
})();
it always shows different and changes everytime,guessing the time appendchild happenes is not simply following?
You only create one tr element.
Each time you append it, you move it from where it was in the DOM and put it in the new location.
If you want to create a new table row for each item in data, then you need to move your createElement call inside the loop.
(You also need to change how you are adding content to it, a tr element isn't allowed to contain text directly, and if you aren't putting multiple data cells in each row, you should probably be using a list instead of a table in the first place).
See this snippet code for creating table
I have edited your code
<div id="wrap"></div>
<script>
var data={
1:"dasf",
2:"jlla",
3:"jalf"
};
(function () {
var table=document.createElement("table");
var tr;
var td;
for(var i in data){
tr=document.createElement("tr");
td=document.createElement("td");
td.innerText = data[i];
tr.appendChild(td);
table.appendChild(tr);
}
document.getElementById("wrap").appendChild(table)
})();
</script>
This will be the output table:
<table>
<tr>
<td>dasf</td>
</tr>
<tr>
<td>jlla</td>
</tr>
<tr>
<td>jalf</td>
</tr>
</table>

Getting element of a table with ID

Been having a great experience here so far!
Anyway, in coding my console bot, i encountered a problem. I wish to obtain some text data from a table, this table records a history of input into the site. But his table has no id and only has a class.
so here is the site element codes:
<div id="game">
<div class="gameTop">
<div class="right">
<div class="scroll">
<table>
<tbody>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
<td>ddd</td>
</tr>
I wish to get var xxx = "...." which corresponds to ddd. I have tried getElementbyClassName('scroll') but it gives me the table. Which is expected.
I am stuck at how to I delve deeper into the codings.
If you're using jQuery, you can use the :get() selector to specifically target the 4th <td> element and text() to retrieve the content.
var dd = $('table td:eq(3)').text();
Here's a fiddle with an example.
Edit
In case you need to get it through #game, you can quickly modify the selector to:
var dd = $('#game table td:eq(3)').text();
You should be able to get the table rows as follows:
var rows = document.getElementsByTagName("table")[0].rows;
var cell = rows[0].cells[4];
var value = cell.innerHTML
In this case, I prefer XPath. See code below:
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
var theDddNode = getElementByXpath("//td[contains(text(),'ddd')]");

Best way to add row to HTML table without re-rendering

I am using websockets (socket.io) for real-time stuff, and it may be that a new item is added to a collection which I would like to then add to the screen. Is there a good way to add a row to an HTML table without re-rendering the whole view?
You can use insertRow on that table. Here is an example:
<table id="TableA">
<tr>
<td>Old top row</td>
</tr>
</table>
<script type="text/javascript">
function addRow(tableID) {
// Get a reference to the table
var tableRef = document.getElementById(tableID);
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New top row');
newCell.appendChild(newText);
}
// Call addRow() with the ID of a table
addRow('TableA');
</script>
Example taken from the Mozilla page for insertRow.

Get Id of table row if it is checked?

I have a datatable containing a list of Cars. each row in the html contains a Car ID. I have added checkbox column to the first cell in my datatable - if it is checked the row is highligted to indicate to the user they have selected that row. What I waht to do is get all the IDs of all the cars a user has selected on clicking a button on the page. (also there are other columns in the table row where I have checkboxes (i.e - a Manual column or an Automatic column which will somtime be checked - like in column 5 ot 6 in the table)
so this is part of the cshtml for my page..
#foreach (var car in Model.Cars)
{
<tr carId="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
//more stuff set in other tds in table
Then this is the JS I have for the page so far.
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
carsListTable.find("tr").each(function (index, para) {
$('tr').find('td:input:checked:first').each(function () {
var car= new Object();
alert($(this).parent().parent().attr("carId"));
car.ID = $(this).parent().parent().attr("carId");
cars.push(car);
});
});
var jsonString = $.toJSON(cars);
I want to then return the json string to my controller (I do this by passing the value into a hidden field on my model and then deserialize - but at the minute I am getting it as empty. My problem is getting the best way to get the id from the row if it is checked?
You can use the selectors :checkbox:checked and use the jQuery.map to convert the array. The jQuery.closest() method will give the closest ancestor matching the given selector.
var cars = carsListTable.find('.table-data :checkbox:checked').map(function(i, v){
return {
ID : $(v).closest('tr').attr('carId')
}
});
Demo Fiddle
Note: The id of elements should be unique in a document so the id of the checkbox should be removed or has to be suffixed or prefixed by a dynamic value like the car id.
First, you should use class instead id for elements that will be present more than once. I suggest change #SelectIndividual for .SelectIndividual on the checkbox input). Another thing you should change is the carId attribute, because is not semantic valid. You should use custom data attributes instead. This is how your code should look like:
HTML
#foreach (var car in Model.Cars)
{
<tr data-carID="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
Jquery
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
$('SelectIndividual:checked').each(function () {
var car= new Object();
car.ID = $(this).parent().parent().data('carID');
cars.push(car);
});
});
//keep doing things
I would suggest to use the data-* attributes that are valid HTML5 as well as the jQuery.data() methods for the id of the car.
Can you assign a class to all checkboxes in first column and then try this
$('.cbClass:checked').each(function () {
tr = $(this).closest('tr');
// use the row
})

Categories

Resources