I have written a function for Add/Remove rows in a table, but the problem is that after adding a row, the CSS property of the table is not coming through properly. As in my input field is not coming in the center of the cell.
In the first row, it's displaying in the center of the cell (as it's hard-coded), but when I create a row using my function, the input field is displaying on the left side of the cell.
My code is:
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow() {
//$('#myModal').modal('toggle');
var x = document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
// new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
x.appendChild(new_row);
}
<table id="POITable" data-toggle="table">
<tr>
<th>colmn1</th>
<th>colmn1</th>
</tr>
<tbody>
<td><input type="text"></td>
<td><input type="text"></td>
<td><a onclick="insRow()" id="addmorePOI">Add row</a></td>
<td><a onclick="deleteRow(this);" id="addmorePOI">Remove row</a></td>
</tbody>
</table>
Please take a look at the image of how it's displaying in my dashboard. Note that I am using a Bootstrap table.
Give each table data tag a similar class name and add the property in css of that class:
text-align: center;
You are missing TR tags in your table body. Should be:
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><a onclick="insRow()" id="addmorePOI">Add row</a></td>
<td><a onclick="deleteRow(this);" id="addmorePOI">Remove row</a>
</td>
</tr>
</tbody>
It looks like you have some padding coming from somehwere. You need to inspect the dom on the newly added element. I noticed that your other cells have 0 padding. try adding cellpadding="0" to the table tag or on each td add class="no-padding" (be sure to create a class for that!) and make sure that class gets added to each new td in a row that you add
Related
I want to sum a selected column inside a table. 2nd and 3rd column in my case. I managed to get the sum but I really want to add the value of a row in case a checkbox in column #1 is checked.
I can get the innerHTML value of a cell abut I do not know how to search or find out if the checkbox inside is checked or not.
console.log(cell.innerHTML);
returns for example
"Extend (2x)<input type=\"checkbox\" id=\"Extend2x\" name=\"Extend2x\" class=\"beru\" <=\"\" td=\"\">
so I can see that the checkbox is there but that is where I ended up
I tried
console.log(cell.innerHTML.getElementsByTagName("checkbox"));
console.log(cell.innerHTML.html());
console.log(cell.html());
console.log($(cell).find(':checkbox').checked) returns undefined
but nothing worked.
Could somoone help me to find out? The working fiddle is here You just click the checkbox and summing of the columns will be done.
The code you are looking for is this
$(':checked')
you can add stuff like input:checked, or something to make it more specific.
EDIT--
just saw the comments - and Taplar already answered this. Well this can be considered as alternative answer, and does not need to use cells / iterate through cells of the table.
I think this is what you wanted. This is using jQuery for every reference to elements in the the dom (html).
$(".beru").on('change', function() {
updateTotals();
});
function updateTotals() {
// loop cells with class 'celkem'
$('.celkem').each(function(){
// for each celkem, get the column
const column = $(this).index();
let total = 0;
// loop trough all table rows, except the header and the row of totals
$(this).closest('table').find('tr:not(:first, :last)').each(function(){
if($(this).find('input').is(':checked')) {
// if the input is checked, add the numeric part to the total
const str = $(this).find(`td:eq(${column})`).text().replace(/\D/g, "");
if(str) {
total += Number(str);
}
}
});
if(!total) {
// if the total is zero, clear the cell
$(this).text("");
} else {
// otherwise, print the total for this column in the cell
$(this).text(total + " EUR");
}
});
}
td {
width: 25%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Zinzino" style="border-collapse: collapse; width: 100%;" border="1">
<tbody>
<tr>
<th><strong>Název</strong></th>
<th class="sum"><strong>První balíček</strong></th>
<th class="sum"><strong>Měsíčně</strong></th>
<th> </th>
</tr>
<tr>
<td>BalanceOil <input type="checkbox" id="BalanceOil" name="BalanceOil" class="beru"></td>
<td>149 EUR</td>
<td>30 EUR</td>
<td> </td>
</tr>
<tr>
<td>Extend (2x)<input type="checkbox" id="Extend2x" name="Extend2x" class="beru"</td>
<td>44 EUR</td>
<td>22 EUR</td>
<td> </td>
</tr>
<tr>
<td>Zinobiotic (3x)<input type="checkbox" id="Zinobiotic" name="Zinobiotic" class="beru"</td>
<td>64 EUR</td>
<td>23 EUR</td>
<td> </td>
</tr>
<tr>
<td><strong>Celkem</strong></td>
<td class="celkem"> </td>
<td class="celkem"> </td>
<td> </td>
</tr>
</tbody>
</table>
If you already have a reference to the DOM element then just select all the checkboxes using a selector.
var cbList = cell.querySelectorAll("[type='checkbox']");
for(var i = 0; i < cbList.length; i++){
//do something with each checkbox
//cbList[i];
}
Remember a node list is not an array, so you can't use forEach ;)
I have a table with several <tr>s and each one has several <td>s. The content of these columns can be another html element (for example a textbox) or just text.
My question: how I can get the rest of the siblings of one clicked element inside this column? I mean, how I can know to which <tr> this element belongs, to <tr> #3 or <tr> #5?I don't have a index per <tr> to control
Example:
If I click the textbox of column #1 in row #5, I want that the content of column #2 in row #5 change. I don't know how to do it because my <tr> doesn't have an index.
Using jQuery, add this to the event handler. This will provide you with a collection of table cells:
var columns = $(this).closest('tr').children();
// .eq() is 0-based, so this would retrieve the fourth column
columns.eq(3);
You can find the index of a row using the index() function.
$('input').click(function(){
var index = $(this).parents('tr').index();
alert('you click an input on row #' + index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td></td>
</tr>
</table>
Use closest to get the parent TR element.
$('your_element').click(function(){
var tr = $(this).closest('tr');
var element1 = $(tr).find('element_to_find');
});
You can also use the :eq operator to find the td.
$('your_element').click(function() {
var tr = $(this).closest('tr');
var col3 = $("td:eq(2)", tr);
}
I have a few tables like this
<table id="table_1">
<tr>
<td><input type="text" name="date[]"</td>
</tr>
</table>
the number of the <td>'s is very variable.
Currently I'm using a function like this:
function addRow(){
var table = document.getElementById('table_1');
var row = table.insertRow(-1);
var cell1 = row.insertCell(0)
....
cell1.innerHTML="<input type='text' name='date[]' />
}
using this method, it would require a custom function for every type of table.
Is there a way, to add a Line to a table, which is exactly the same as the last row?
In a table with 7 cells, 7 cells would be added, with the right content.
Is this possible in pure JS?
You could do it this way with jQuery:
Edit:
Sorry, I did not see you wanted pure JS.
jQuery
$('button').click(function(){
var table = $(this).prev('table');
var lastrow = $('tr:last-child', table).html();
table.append('<tr>' + lastrow + '</tr>');
});
HTML
<table>
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>
<button>Add a row</button>
<table>
<tr>
<th>Meal</th>
<th>Price</th>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>
<button>Add a row</button>
JS Fiddle Demo
Maybe this is what you need : http://jsfiddle.net/thecbuilder/bx326s31/1/
<input type="button" onclick="cloneRow()" value="Clone Row" />
<input type="button" onclick="createRow()" value="Create Row" />
<table>
<tbody id="tableToModify">
<tr id="rowToClone">
<td><input type="text" name="txt[]"/></td>
<td>bar</td>
</tr>
</tbody>
</table>
function cloneRow() {
var row = document.getElementById("rowToClone"); // find row to copy
var table = document.getElementById("tableToModify"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newID"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function createRow() {
var row = document.createElement('tr'); // create row node
var col = document.createElement('td'); // create column node
var col2 = document.createElement('td'); // create second column node
row.appendChild(col); // append first column to row
row.appendChild(col2); // append second column to row
col.innerHTML = "qwe"; // put data in first column
col2.innerHTML = "rty"; // put data in second column
var table = document.getElementById("tableToModify"); // find table to append to
table.appendChild(row); // append row to table
}
Refer : https://stackoverflow.com/a/1728578/3603806
The below fiddle is from another question. It contains the output of a dynamic addition and deletion of html table rows using javascript. The code in the fiddle gave me what i want. But i have one problem with the code. While deleting the rows one by one, the first row is also getting deleted. How can i hide the delete button only in the first row ?
http://jsfiddle.net/7AeDQ/
HTML
<div id="POItablediv">
<input type="button" id="addPOIbutton" value="Add POIs"/><br/><br/>
<table id="POITable" border="1">
<tr>
<td>POI</td>
<td>Latitude</td>
<td>Longitude</td>
<td>Delete?</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="latbox"/></td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()"/></td>
</tr>
</table>
JAVASCRIPT
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
console.log( 'hi');
var x=document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
}
Above is the code in the fiddle. Hope this helps if you can't load fiddle. It happens sometimes.
This looks elegant.
Hide the first:
$("table tr:eq(1) td:eq(3) input").css("display","none");
Then show the newly created tr:
var noRows = $("#POITable tr").length-1;
$("table tr:eq("+noRows+") td:eq(3) input").css("display","block");
Fiddle:
http://jsfiddle.net/Lh8KL/
Just add this statement:
x.rows[1].cells[3].children[0].style.display = x.rows.length > 2 ? '' : 'none';
This gets a reference to the input element in the first row in the third cell and hides it if there is only one row.
Updated fiddle: http://jsfiddle.net/7AeDQ/23/
just add the following line in the script
new_row.cells[3].getElementsByTagName('input')[0].removeAttribute('style');
Plus a little modification in the HTML (add disabled to true in the first delete button)
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" style="display:none"/></td>
Check fiddle: http://jsfiddle.net/7AeDQ/25/
I found some code that helped me get pretty close. Kudos to daiscog for that! Here is what I'm trying to do. There is a table with rows of entries for a giveaway. I want to be able to click a button and remove that row from the table and and generate a new table on the fly with that random row that was picked form the primary table.
Right now the code below selects a random row and highlights it in dark blue. Which is great. Issue is it also counts the <thead> and <tfoot> as rows in the random pick, ideally it wouldn't. Which isn't a huge deal. But can be once I get working what I'd like to. Issue is right now when the logs of entries gets really long it's hard to keep track of who was picked first.
Any ideas on how to accomplish this via Javascript?
<table id="cp_logs_table" class="widefat" style="background-color:#333;color:#ddd;font-weight:bold;margin:15px;">
<thead><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></thead>
<tfoot><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></tfoot>
<tr>
<td title="wolfkin">wolfkin [wolfkin]</td>
<td>- 150</td>
<td>
Lottery Ticket
</td>
<td title="2011-10-14 17:20:29">11 hours ago</td>
</tr><tr>
<td title="dragon290513">dragon290513 [dragon290513]</td>
<td>+ 5</td>
<td>
Video Entry
</td>
<td title="2011-10-14 01:42:30">1 day ago</td>
</tr></table>
<script>
function cplottopickwinner() {
// get all TRs that are descendants of table#cp_logs_table:
var tds = document.getElementById("cp_logs_table").getElementsByTagName("tr");
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight tr at that index
tds[rand].style.backgroundColor = "#375297";
//tds[rand].style.color = "#000";
}
</script>
Pick Random Winner(s)
I modified the function to the code below, but it's not populating the table with anything, but it's still highlighting the table row in blue. I'm sure I'm missing something simple to automatically remove that row and add it to the new table.
function cplottopickwinner() {
// get all TRs that are descendants of table#cp_logs_table:
var tds = document.getElementById("cp_logs_table").getElementsByTagName("tr");
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight tr at that index
tds[rand].style.backgroundColor = "#375297";
//tds[rand].style.color = "#000";
jQuery("#cb_winners").fadeIn("slow");
var html = tds[rand].html();
tds[rand].remove();
jQuery("#winners").append("<tr>"+html+"</tr>");
}
If you have another table to put in the winners,
<table>
<thead><!-- .... --></thead>
<tfoot><!-- .... --></tfoot>
<tbody id="winners"></tbody>
</table>
Then you just have to append the whole <tr> to it, then it will disappear from old table because it is not cloned.
document.getElementById('winners').appendChild(trs[rand]);
http://jsfiddle.net/sMPQS/
I made it using jQuery.. hope it's helpful.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<table id="cp_logs_table" class="widefat" style="background-color:#333;color:#ddd;font-weight:bold;margin:15px;">
<thead><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></thead>
<tfoot><tr><th scope="col">Name [Username]</th><th scope="col">Points</th><th scope="col">Entry Type</th><th scope="col">Time</th></tr></tfoot>
<tr>
<td title="wolfkin">wolfkin [wolfkin]</td>
<td>- 150</td>
<td>Lottery Ticket</td>
<td title="2011-10-14 17:20:29">11 hours ago</td>
<td><input type='submit' value='MOVE' class='move'></td>
</tr>
<tr>
<td title="dragon290513">dragon290513 [dragon290513]</td>
<td>+ 5</td>
<td>Video Entry</td>
<td title="2011-10-14 01:42:30">1 day ago</td>
<td><input type='submit' value='MOVE' class='move'></td>
</tr>
</table>
<script>
$('.move').click(function(){
var row = $(this).parent('td').parent('tr');
var html = row.html();
row.remove();
$('#winners').append("<tr>"+html+"</tr>");
});
</script>
<table id='winners' ></table>