I have two buttons called "Add Column Left" and "Add Column Right". I need to get the Index of the clicked cell, so that I can get the column index and add the new column to the previous one.
My current code:
function AddColumn(addLeft){ // Which button is clicked? Add Left || Add Right
var header = $('#tableHeader'); // Get the table header element
var headerContentToAppend = "<th>Header</th>"; // The default text of the new header
var table = $('#tableBody'); // Get the table body element
var rowContentToAppend = "<td>Content</td>"; // The default text of the new cells
// issue 1: missing index of the clicked/focussed column
if (addLeft) { // Button "Add Column Left" clicked
header.prepend(headerContentToAppend); // Add the Column to the left of the previous column
}
else { // Button "Add Column Right" clicked
header.append(headerContentToAppend); // Add the Column to the right of the previous column
}
$('table th').last().attr("contenteditable", true).focus(); // set all cells editable and focus the last one
table.find("tr").each(function() { // Get all existing rows ....
// issue 2: maybe the cells don't match to the right column, I have to test this after finishing the first issue
$(this).append(rowContentToAppend); // ... and add cells to the new column
});
}
So my problem is to get the right index of the clicked column. After adding a new column i have to fill it up with new cells below.
I placed two comments called "issue" in the code, that should make things clear.
My HTML Code:
<table id="dataTable">
<thead id="tableHeader">
</thead>
<tbody id="tableBody">
</tbody>
</table>
I want to control the table by Javascript to keep it dynamic.
Since you're using jQuery you could use the method index() to get the element index :
var index = $(this).closest('tr').find('td').index($(this));
Hope this helps.
var index = 0;
function AddColumn(addLeft){
var header = $('#tableHeader');
var headerContentToAppend = "<th>Header</th>";
var table = $('#tableBody');
var rowContentToAppend = "<td>Content</td>";
if (addLeft)
header.find('th').eq(index).before(headerContentToAppend);
else
header.find('th').eq(index).after(headerContentToAppend);
$('table th').attr("contenteditable", true).last().focus();
table.find("tr").each(function() {
if (addLeft)
$(this).find('td').eq(index).before(rowContentToAppend);
else
$(this).find('td').eq(index).after(rowContentToAppend);
});
$('td').removeClass('selected');
}
$('body').on('click','td',function(){
$('td').removeClass('selected');
$(this).addClass('selected');
index = $(this).closest('tr').find('td').index($(this));
});
.selected{
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<thead id='tableHeader'>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</thead>
<tbody id='tableBody'>
<tr>
<td>column 1</td>
<td>column 2</td>
<td>column 3</td>
</tr>
<tr>
<td>column 11</td>
<td>column 22</td>
<td>column 33</td>
</tr>
<tr>
<td>column 111</td>
<td>column 222</td>
<td>column 333</td>
</tr>
</tbody>
</table>
<br>
<button onClick='AddColumn(true)'>< Add to the Left</button>
<button onClick='AddColumn(false)'>Add to the Right ></button>
Related
I have a script that able to add new column to a HTML table. When user press add group the header will become Group1, Group2 and so on.. Currently im adding a delete group function that able to delete all the added column. So now the problem is when I delete a column and add again a new column , the name Group(x) will not be reset.
For example:user add group1 and group2 after that he delete group2. The next time he press add group again, it will show group3 instead of group2
Image:
Expected Output: The column name should be reset whenever the column is deleted.
Html:
<table id="persons" border="1">
<thead id="theadID">
<tr>
<th>Name</th>
<th>sex</th>
<th>Message</th>
</tr>
</thead>
<tbody id="tbodyID">
<tr>
<td>Viktor</td>
<td>Male</td>
<td>etc</td>
</tr>
<tr>
<td>Melissa</td>
<td>Female</td>
<td>etc</td>
</tr>
<tr>
<td>Joe</td>
<td>Male</td>
<td>etc</td>
</tr>
</tbody>
</table>
<button onclick="javascript:appendColumn()">Add column</button>
<input type="button" onclick="deleteLastColumn();" value="do it"/>
Jquery& Javascript:
function deleteLastColumn() {
$('#persons tr').find('th:last-child, td:last-child').remove()
}
let groupNum = 1;
const tableEl = document.getElementById('persons');
// append column to the HTML table
function appendColumn() {
// open loop for each row and append cell
for (let i = 0; i < tableEl.rows.length; i++) {
createCell(tableEl.rows[i].insertCell(tableEl.rows[i].cells.length), i, 'col');
}
tableEl.rows[0].querySelector('td:last-child').textContent = 'Group' + groupNum;
groupNum++;
}
// create DIV element and append to the table cell
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode(text); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('class', style); // set DIV class attribute
div.setAttribute('className', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
maybe I'm missing it but I don't see the code which deletes ALL the cols, I only see one. But still the solution seems simple, just decrement the groupNum variable when you delete a col
function deleteLastColumn() {
$('#persons tr').find('th:last-child, td:last-child').remove()
groupNum--;
}
Need help with populating a text area based on html table row selection.
In the table below, I want to extract the content of the column 'Comments' for the selected row and write into the text area 'Comment' on the same page. I have only managed to create the table but nothing else.
Below is the code I have now created from this link. What is happening now is that only the currently selected cell gets put in the text box instead of just the 'Comment' column. I want to input only in the 'Comment' column into the box regardless of the cell clicked upon in the row.
<table id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Comments</th>
</tr>
<tbody>
<tr>
<td>John</td>
<td>42</td>
<td>avery long comment</td>
</tr>
<tr>
<td>Peter</td>
<td>35</td>
<td>another very long comment</td>
</tr>
<tr>
<td>Mary</td>
<td>54</td>
<td>some comment</td>
</tr>
</tbody>
</table>
<script>
var table = document.getElementById('table');
var selected = table.getElementsByClassName('selected');
table.onclick = highlight;
function highlight(e) {
if (selected[0]) selected[0].className = '';
e.target.parentNode.className = 'selected';
var element = document.querySelectorAll('.selected');
if (element[0] !== undefined) { //it must be selected
document.getElementById("myTextbox").value = element[0].children[0].firstChild.data
}
}
</script>
<div >
<textarea class="form-control" id="myTextbox"></textarea>
</div>
Thanks for your help.
You're getting the first column but you can get the third column with the comment by changing the index of the child to 2 instead of 0.
document.getElementById("myTextbox").value = element[0].children[2].firstChild.data
I need to get the table row value from onclick event. Below the table, I am using
Group name|Manage group
Test 1 | Button
Test 2 | Button
If I click 'Button' from the table row, I need to get the respective group name value from the table row.
Below the script, I am trying. But it is printing only the first group name value "Test 1" for both buttons.
var table = document.getElementById("user_table");
var rows = table.rows;
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = (function (e) {
var rowid = (this.cells[0].innerHTML);
var j = 0;
var td = e.target;
while( (td = td.previousElementSibling) != null )
j++;
alert(rows[1].cells[j].innerHTML);
});
}
alert(rows[1].cells[j].innerHTML) printing group name value Test 1 and if I click second row button it is showing Test 1 only.But I need to get Test 2 if I click second row button.
Html file
<table id="user_table" style='overflow-x:scroll;overflow-y:scroll;width:100%;height:auto' class="table table-bordered" >
<thead>
<tr class="info">
<th>Group Name</th>
<th>User Group</th>
</tr>
</thead>
<tbody id="table_body">
<br>
<% #array.each do |user| %>
<tr>
<td >
<%=user['group_name']%>
</td>
<td>
<button id='manageusrbtn' name="button" type="button" class="editbtn" onclick="manageUserGroups()" style="background-color: #008CBA; color: white; border-radius: 6px;" >Manage User Groups</button>
</td>
<% end %>
</tr>
</tbody>
</table>
I would suggest to attach the click event handler to the button and not to each cell.
For this you can use:
querySelectorAll
forEach
addEventListener
closest
The snippet:
var table = document.querySelectorAll('#user_table tr button');
table.forEach(function(ele) {
ele.addEventListener('click', function (e) {
var rowid = (this.closest('td').previousElementSibling.innerHTML);
console.log(rowid);
})
});
<table id="user_table">
<tr>
<th>Group name</th>
<th>Manage group</th>
</tr>
<tbody>
<tr>
<td>Test 1</td>
<td><button>Button</button></td>
</tr> <tr>
<td>Test 2</td>
<td><button>Button</button></td>
</tr>
</tbody>
</table>
Making an food ordering app. There is a first table with all items you can choose. Each item have a button. On this button click it clones the line and put it in a second table containing your chosen items. I would like to change the text content of the button when the element go to the second table. Like "+" in the first table become "-" in the second table (to next delete the item of the second table on "-" click)
HTML
<h1>CHOOSE</h1>
<table id="starters">
<tr>
<th>PRODUCT</th>
<th>PRICE</th>
<th>ADD TO CART</th>
</tr>
<tr>
<td>Cherry</td>
<td>6</td>
<td><button class="item_button">+</button></td>
</tr>
<tr>
<td>Peach</td>
<td>8</td>
<td><button class="item_button">+</button></td>
</tr>
<tr>
<td>Strawberry</td>
<td>12</td>
<td><button class="item_button">+</button></td>
</tr>
</table>
<h1>YOUR CHOICE</h1>
<table id="products_cart">
</table>
JS
let basket = document.getElementById("products_cart")
let buttons = document.querySelectorAll('.item_button');
for (button of buttons) {
button.addEventListener('click', cloneLine);
}
function cloneLine(e) {
let td = e.target.parentNode;
let tr = td.parentNode;
let clone = tr.cloneNode(true);
basket.appendChild(clone);
}
I tried different things like to get (querySelectorAll) the buttons and change their innerHTML (or textContent or innerText) with no success. I also tried to create another button and to replace the former by the newer.
I have a table which is populated using jQuery dataTables. I want to know:
How to add an index column. The dataTables.net site has an example which tells how to give a present index file the index properties not how to make it.
I want to make one of my columns a volume slider. It has only a number which is between 0-100 and want to use jQueryUI slider to make it. Where should I intialise the slider function? Before or inside of dataTables initialization function or after it, and how?
Adding an index column is covered pretty well in the online documentation here: https://datatables.net/examples/api/counter_columns.html
As for the volume slider, I did find a hack-y way to get it working. I added an empty th in the thead and a td at the beginning of each row in the tbody. The first td has the slider div and a rowspan of 3 (my example has only 3 rows). The other tds are empty with a style of display:none.
<table id="myTable" class="display">
<thead>
<tr>
<th></th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="3">
<div id="slider"></div>
</td>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
<!-- Other rows here -->
</tbody>
</table>
In the JS, I used the example shown in the documentation for an index column, with several changes. I am initializing the slider on "initComplete" of the DataTable, and again when the table is sorted or searched.
var table = $("#myTable").DataTable({
//Table options here
"initComplete":function(){
$("#slider").slider(sliderOpts);
}
});
table.on('order.dt search.dt', function(){
table.column(0, {search:'applied', order:'applied'}).nodes().each(function(cell, i){
if(i == 0){
$(cell).attr("rowspan","3").html("<div id='slider'></div>").css("display","table-cell");
$("#slider").slider(sliderOpts);
} else {
cell.innerHTML = '';
$(cell).css("display","none")
}
})
}).draw();
Here is a jsfiddle of my solution: https://jsfiddle.net/r7jwv76L/2/