I'm using Html5 draggable to drag items into different table cells:
http://jsfiddle.net/d1wnk1bg/6/
<table border="1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td><span class="event" id="item1" draggable="true">Item 1</span>
</td>
<td><span class="event" id="item2" draggable="true">Item 2</span>
<span class="event" id="item3" draggable="true">Item 3</span>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
$(document).ready(function(){
$('.event').on("dragstart", function (event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
});
$('table td').on("dragenter dragover drop", function (event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text',$(this).attr('id'));
de=$('#'+data).detach();
de.appendTo($(this));
};
});
})
The only problem with this approach is that if you drag 'Item 1' into the cell where 'Item 2' and 'Item 3' are, Item 1 gets appended to the end.
How can I modify this so that 'Item 1' can be added before 'Item 2' or between 'Item 2' and 'Item 3'. I tried going down the rabbit hole of nested draggables but gave up pretty quickly, hoping there's an easier way!
I forked the Fiddle and adjusted the code a bit:
http://jsfiddle.net/gL88q17m/1/
$(document).ready(function () {
$('.event').on("dragstart", function (event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
});
$('table td').on("dragenter dragover drop", function (event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text', $(this).attr('id'));
de = $('#' + data).detach();
if (event.originalEvent.target.tagName === "SPAN") {
de.insertBefore($(event.originalEvent.target));
}
else {
de.appendTo($(this));
}
};
});
})
What I did is checking whether the item was dropped directly into the td in which case the dropped element will be inserted after all the other entries or if it was dropped on top of another item in which case the item is inserted just before the item the dropped item was dropped on.
Adding some padding to the td makes it easier to drop an item directly into the td even if there are already 3 items inside.
table th, table td {
width: 200px;
height:70px;
padding: 5px;
}
table span {
display:block;
background-color: #ccc;
border: 1px solid black;
color: fff;
height: 30px;
width: 100%;
}
I have done some changes after reading your comment. Now it is working like a charm. I will recommend reading this.
$(document).ready(function () {
$(".event").on("dragstart",function(event){
var dt = event.originalEvent.dataTransfer;
var node = event.target;
dt.setData('text/html', node.innerHTML);
dt.setData('text/plain',node.id);
event.stopPropagation();
});
$(".event").on("dragend",function(e){
event.preventDefault();event.stopPropagation();
})
$(".row>td").on("dragenter dragover dragleave",function(e){
event.preventDefault();event.stopPropagation();
})
$(".row > td").on("drop",function(event){
var dragObjId = event.originalEvent.dataTransfer.getData("text/plain");
var data = $("#"+dragObjId);
var dropTarget = $(event.target).closest("td");
$(dropTarget).prepend(data);
});
})
$(document).ready(function() {
$(".event").on("dragstart", function(event) {
var dt = event.originalEvent.dataTransfer;
var node = event.target;
dt.setData('text/html', node.innerHTML);
dt.setData('text/plain', node.id);
event.stopPropagation();
});
$(".event").on("dragend", function(e) {
event.preventDefault();
event.stopPropagation();
}) $(".row>td").on("dragenter dragover dragleave", function(e) {
event.preventDefault();
event.stopPropagation();
}) $(".row > td").on("drop", functiwww.ta3roof.com / on(event) {
var dragObjId = event.originalEvent.dataTransfer.getData("text/plain");
var data = $("#" + dragObjId);
var dropTarget = $(event.target).closest("td");
$(dropTarget).prepend(data);
});
})
Related
The code basically edit a table cell.
I want to use the not() method so that everytime I click outside the temporary input created I replace it with a table cell. I guess the code run in a block and doesn't detect any input with an id of "replace" so how can I fix that ?
Also I want to store the element (th or td) that fire the first event(dblclick) so that I can use it to replace the input with the right type of cell but it seems to only stores the element that first triggers the event and I don't really understand why.
Full code here
$(function () {
$(document).on("dblclick", "th, td", function (event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
var $typeCell = $(event.currentTarget); // Store element which trigger the event
$("body").not("#replace").on("click", function () { // .not() method
cellText = $("#replace").val();
if ($typeCell.is("th")) {
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
}
else {
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
});
});
I have modified HTML and JavaScript to avoid any possible errors. The correct practice is to wrap all th's in a thead and all td's in tbody.
$(document).on("dblclick", "th, td", function(event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
});
$("body").on("click", function() {
if (event.target.id != 'replace' && $('#replace').length != 0) {
var cellText = $("#replace").val();
if ($('#replace').parents().is('thead'))
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
else
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
table {
border-collapse: collapse;
margin: 20px;
min-width: 100px;
}
table,
th,
td {
border: 1px solid grey;
padding: 4px;
}
th {
background: springgreen;
}
tr:nth-child(odd) {
background: rgba(0, 255, 127, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table>
<thead>
<tr>
<th scope="col">Uno</th>
<th scope="col">Dos</th>
<th scope="col">Tres</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
</tr>
<tr>
<td>Data4</td>
<td>Data5</td>
<td>Data6</td>
</tr>
</tbody>
</table>
</div>
I am using: jquery.dataTables.js from: https://datatables.net
I am trying to drag and drop a column from one table to another.
EDIT:
so basically what I want to do is:
be able to drag and drop the names from table 2 into column called name in the table above
after drag and drop the name the same should disappear from the table 2.
case 2: if I add a new row using the button Add new Row
I need be able to drag a drop the names from table 2 into that column name too.
so basically I want to do a drag and drop just in the column not in the row.
I don't want create a new row just move the names from 1 table to another.
EDIT 2:
1- Can you drag/drop multiples values from Table #2 to Table #1?
no, the drag and drop will be possible just 1 by 1.
The drag and drop will be just possible after the user clicks in edit or add a new row.
so I will be able to replace names drom table 2 into the column names table 1
2- If no, the value dragged shall then replace the value where it is dropped?
yes
3- If yes,how should it work? Adding new rows with the other values blank?
no row need be added, we just need replace the column name.
how will works:
so after click in edit or add new row i will be able to drag a name from table 2 into column in
table 1.
few more resquests if possible:
if select the row in table 2, this row should be change the color, showing was selected. and in the table 1 collun name where this need be dropped need to change the color to show the
user can be dropped.
sample working here:
http://plnkr.co/edit/6sbmBzbXDzm4p6CjaVK0?p=preview
$(document).ready(function() {
var dataUrl = 'http://www.json-generator.com/api/json/get/ccTtqmPbkO?indent=2';
var options = [
{ key : 'option 1', value : 1 },
{ key : 'option 2', value : 2 },
{ key : 'option 3', value : 3 }
];
$(document).ready(function() {
var $table = $('#example');
var dataTable = null;
$table.on('mousedown', 'td .fa.fa-minus-square', function(e) {
dataTable.row($(this).closest("tr")).remove().draw();
});
$table.on('mousedown.edit', 'i.fa.fa-pencil-square', function(e) {
enableRowEdit($(this));
});
$table.on('mousedown', 'input', function(e) {
e.stopPropagation();
});
$table.on('mousedown.save', 'i.fa.fa-envelope-o', function(e) {
updateRow($(this), true); // Pass save button to function.
});
$table.on('mousedown', '.select-basic', function(e) {
e.stopPropagation();
});
dataTable = $table.DataTable({
ajax: dataUrl,
rowReorder: {
dataSrc: 'order',
selector: 'tr'
},
columns: [{
data: 'order'
}, {
data: 'name'
}, {
data: 'place'
}, {
data: 'delete'
}]
});
$table.css('border-bottom', 'none')
.after($('<div>').addClass('addRow')
.append($('<button>').attr('id', 'addRow').text('Add New Row')));
// Add row
$('#addRow').click(function() {
var $row = $("#new-row-template").find('tr').clone();
dataTable.row.add($row).draw();
// Toggle edit mode upon creation.
enableRowEdit($table.find('tbody tr:last-child td i.fa.fa-pencil-square'));
});
$('#btn-save').on('click', function() {
updateRows(true); // Update all edited rows
});
$('#btn-cancel').on('click', function() {
updateRows(false); // Revert all edited rows
});
function enableRowEdit($editButton) {
$editButton.removeClass().addClass("fa fa-envelope-o");
var $row = $editButton.closest("tr").off("mousedown");
$row.find("td").not(':first').not(':last').each(function(i, el) {
enableEditText($(this))
});
$row.find('td:first').each(function(i, el) {
enableEditSelect($(this))
});
}
function enableEditText($cell) {
var txt = $cell.text();
$cell.empty().append($('<input>', {
type : 'text',
value : txt
}).data('original-text', txt));
}
function enableEditSelect($cell) {
var txt = $cell.text();
$cell.empty().append($('<select>', {
class : 'select-basic'
}).append(options.map(function(option) {
return $('<option>', {
text : option.key,
value : option.value
})
})).data('original-value', txt));
}
function updateRows(commit) {
$table.find('tbody tr td i.fa.fa-envelope-o').each(function(index, button) {
updateRow($(button), commit);
});
}
function updateRow($saveButton, commit) {
$saveButton.removeClass().addClass('fa fa-pencil-square');
var $row = $saveButton.closest("tr");
$row.find('td').not(':first').not(':last').each(function(i, el) {
var $input = $(this).find('input');
$(this).text(commit ? $input.val() : $input.data('original-text'));
});
$row.find('td:first').each(function(i, el) {
var $input = $(this).find('select');
$(this).text(commit ? $input.val() : $input.data('original-value'));
});
}
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/bXcKDeAbyq?indent=2';
table = $('#example2').DataTable({
ajax: url,
order: [[ 0, "desc" ]],
rowReorder: {
dataSrc: 'place',
selector: 'tr'
},
columns: [ {
data: 'name'
}]
});
});
});
div.addRow {
line-height: 45px;
background-color: #fff;
padding-left: 10px;
border-bottom: 1px solid;
border-top: 1px solid #e5e5e5;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="//cdn.rawgit.com/DataTables/RowReorder/ce6d240e/js/dataTables.rowReorder.js"></script>
<link href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="//cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css" rel="stylesheet"/>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>order</th>
<th>name</th>
<th>country</th>
<th>action</th>
</tr>
</thead>
</table>
<table id="new-row-template" style="display:none">
<tbody>
<tr>
<td>999</td> <!-- Use a large number or row might be inserted in the middle -->
<td>__NAME__</td>
<td>__COUNTRY__</td>
<td>
<i class="fa fa-pencil-square" aria-hidden="true"></i>
<i class="fa fa-minus-square" aria-hidden="true"></i>
</td>
</tr>
</tbody>
</table>
<br>
<div class="pull-right">
<button type="button" id="btn-cancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="btn-save" class="btn btn-primary" data-dismiss="modal">Save</button>
</div>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
I've made some changes to your code. Try it out please to see whether this resolution is appropriate for you:
$(document).ready(function() {
var dataUrl = 'http://www.json-generator.com/api/json/get/ccTtqmPbkO?indent=2';
var options = [{
key: 'option 1',
value: 1
},
{
key: 'option 2',
value: 2
},
{
key: 'option 3',
value: 3
}
];
var rowCache = [];
function mouseUp(event) {
var ctrl = $(document.elementsFromPoint(event.clientX, event.clientY)).filter('input.border-highlight');
if (ctrl.length > 0 && rowCache.length > 0) {
var el = rowCache[0];
var data = el.row.data();
if (data.length > 0) {
ctrl.val(data[0].name);
el.row.remove().draw();
}
}
rowCache = [];
$('#example tr td:nth-child(2) input').removeClass('border-highlight');
}
$(document).ready(function() {
var $table = $('#example');
var dataTable = null;
$('body').mouseup(mouseUp);
$table.on('mousedown', 'td .fa.fa-minus-square', function(e) {
dataTable.row($(this).closest("tr")).remove().draw();
});
$table.on('mousedown.edit', 'i.fa.fa-pencil-square', function(e) {
enableRowEdit($(this));
});
$table.on('mousedown', 'input', function(e) {
e.stopPropagation();
});
$table.on('mousedown.save', 'i.fa.fa-envelope-o', function(e) {
updateRow($(this), true); // Pass save button to function.
});
$table.on('mousedown', '.select-basic', function(e) {
e.stopPropagation();
});
dataTable = $table.DataTable({
ajax: dataUrl,
rowReorder: {
dataSrc: 'order',
selector: 'tr'
},
columns: [{
data: 'order'
}, {
data: 'name'
}, {
data: 'place'
}, {
data: 'delete'
}]
});
$table.css('border-bottom', 'none')
.after($('<div>').addClass('addRow')
.append($('<button>').attr('id', 'addRow').text('Add New Row')));
// Add row
$('#addRow').click(function() {
var $row = $("#new-row-template").find('tr').clone();
dataTable.row.add($row).draw();
// Toggle edit mode upon creation.
enableRowEdit($table.find('tbody tr:last-child td i.fa.fa-pencil-square'));
});
$('#btn-save').on('click', function() {
updateRows(true); // Update all edited rows
});
$('#btn-cancel').on('click', function() {
updateRows(false); // Revert all edited rows
});
function enableRowEdit($editButton) {
$editButton.removeClass().addClass("fa fa-envelope-o");
var $row = $editButton.closest("tr").off("mousedown");
$row.find("td").not(':first').not(':last').each(function(i, el) {
enableEditText($(this))
});
$row.find('td:first').each(function(i, el) {
enableEditSelect($(this))
});
}
function enableEditText($cell) {
var txt = $cell.text();
$cell.empty().append($('<input>', {
type: 'text',
value: txt
}).data('original-text', txt));
}
function enableEditSelect($cell) {
var txt = $cell.text();
$cell.empty().append($('<select>', {
class: 'select-basic'
}).append(options.map(function(option) {
return $('<option>', {
text: option.key,
value: option.value
})
})).data('original-value', txt));
}
function updateRows(commit) {
$table.find('tbody tr td i.fa.fa-envelope-o').each(function(index, button) {
updateRow($(button), commit);
});
}
function updateRow($saveButton, commit) {
$saveButton.removeClass().addClass('fa fa-pencil-square');
var $row = $saveButton.closest("tr");
$row.find('td').not(':first').not(':last').each(function(i, el) {
var $input = $(this).find('input');
$(this).text(commit ? $input.val() : $input.data('original-text'));
});
$row.find('td:first').each(function(i, el) {
var $input = $(this).find('select');
$(this).text(commit ? $input.val() : $input.data('original-value'));
});
}
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/bXcKDeAbyq?indent=2';
table = $('#example2').DataTable({
ajax: url,
order: [
[0, "desc"]
],
rowReorder: {
dataSrc: 'place',
selector: 'tr'
},
columns: [{
data: 'name'
}]
});
table.on('mousedown', 'tbody tr', function() {
var $row = $(this);
var r = table.rows(function(i, data) {
return data.name == $row.children().first().text();
});
if (r[0].length > 0) {
$row.parents('table').find('tr').removeClass('highlight');
$row.addClass('highlight');
$('#example tr td:nth-child(2) input').addClass('border-highlight');
}
rowCache.push({
row: r
});
});
});
});
div.addRow {
line-height: 45px;
background-color: #fff;
padding-left: 10px;
border-bottom: 1px solid;
border-top: 1px solid #e5e5e5;
}
tr.highlight td {
background-color: #D0ECE7 !important;
}
.border-highlight {
border-color: #D0ECE7 !important;
border-width: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/rowreorder/1.2.0/js/dataTables.rowReorder.min.js"></script>
<link data-require="datatables#*" data-semver="1.10.12" rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>order</th>
<th>name</th>
<th>country</th>
<th>action</th>
</tr>
</thead>
</table>
<table id="new-row-template" style="display:none">
<tbody>
<tr>
<td>999</td>
<!-- Use a large number or row might be inserted in the middle -->
<td>__NAME__</td>
<td>__COUNTRY__</td>
<td>
<i class="fa fa-pencil-square" aria-hidden="true"></i>
<i class="fa fa-minus-square" aria-hidden="true"></i>
</td>
</tr>
</tbody>
</table>
<br>
<div class="pull-right">
<button type="button" id="btn-cancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="btn-save" class="btn btn-primary" data-dismiss="modal">Save</button>
</div>
<br>
<br>
<h1>
table 2
</h1><br>
<br>
<table id="example2" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th> name</th>
</tr>
</thead>
</table>
JSFiddle: http://jsfiddle.net/f7debwj2/47/
First thing first, bind click event for table 2 td to grab the data which is really simple. Then I would write mouseup function as follows on table 1:
$('table-id-class').on('mouseup', 'td', function (e) {
console.log(e.html());
e.stopPropagation();
});
The above event would give you exact position of the td, you are left with changing value for the TD. I am sure datatables must be having some way to change values in order to go that value in data. Good luck!
I have a table that I add columns to it on the fly. Each column has an [X] icon on the top, when a user clicks on it, I need to delete the entire column.
I created a Fiddler page to show you what I have done.
As you can see I have [X] icon on the top and when I click it, it is deleting the 3rd column in the table because I am specifying a fixed column i.e. 3. But I need to be able to remove the current column not the 3rd column.
How can I determine what is the current column and delete every tr with in the table matching the correct position?
Could try something like this:
$('.removeMe').click(function() {
var indexToRemove = $(this).index();
$(".defaultTable tbody tr").each(function() {
$(this).find("td:eq("+indexToRemove+")").remove();
});
});
Edit:
Here's a fiddle which will remove them, the headers, and any dynamically-created columns as well. It uses jQuery's .on() method with delegated events so that even elements which are created dynamically will have this event listener added to them. .click() is a direct binding and will only bind it to elements which already exist so newly-created elements won't have the event listeners binded to them.
Fiddle: http://jsfiddle.net/stevenelberger/dsL31yek/
You may use https://api.jquery.com/nth-child-selector/:
$('#testTable1').on('click', '.removeMe', function () {
$(".defaultTable thead tr th:nth-child(" + ($(this).index() + 1) + ")").remove();
$(".defaultTable tbody tr td:nth-child(" + ($(this).index() + 1) + ")").remove();
});
Snippet:
$(document).ready(function () {
$('.defaultTable').dragtable();
$('#test1').click(function () {
$("#testTable1 > thead > tr").each(function () {
$(this).append('<th>New Column</th>');
});
$("#testTable1 > tbody > tr").each(function (i, e) {
if (i == 0) {
$(this).append('<td class="removeMe">[X]</td>');
} else {
$(this).append('<td>New cell in the column</td>');
}
});
$('.defaultTable').removeData().dragtable();
});
$('#testTable1').on('click', '.removeMe', function () {
$(".defaultTable thead tr th:nth-child(" + ($(this).index() + 1) + ")").remove();
$(".defaultTable tbody tr td:nth-child(" + ($(this).index() + 1) + ")").remove();
});
$('.defaultTable').removeData().dragtable();
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="http://akottr.github.io/css/akottr.css" rel="stylesheet"/>
<link href="http://akottr.github.io/css/reset.css" rel="stylesheet"/>
<link rel="stylesheet" type="text/css" href="//rawgithub.com/akottr/dragtable/master/dragtable.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script src="//rawgithub.com/akottr/dragtable/master/jquery.dragtable.js"></script>
<!-- only for jquery.chili-2.2.js -->
<script src="//code.jquery.com/jquery-migrate-1.1.1.js"></script>
<script type="text/javascript" src="//akottr.github.io/js/jquery.chili-2.2.js"></script>
<div class="sample">
<button type="button" id="test1">Add column</button>
<div class="demo">
<h4>demo</h4>
<div class="demo-content">
<table class="defaultTable sar-table" id="testTable1">
<thead>
<tr>
<th>TIME</th>
<th>%user</th>
<th>%nice</th>
<th>%system</th>
<th>%iowait</th>
<th>%idle</th>
</tr>
</thead>
<tbody>
<tr>
<td class="removeMe">[X]</td>
<td class="removeMe">[X]</td>
<td class="removeMe">[X]</td>
<td class="removeMe">[X]</td>
<td class="removeMe">[X]</td>
<td class="removeMe">[X]</td>
</tr>
<tr>
<td>12:10:01 AM</td>
<td>28.86</td>
<td>0.04</td>
<td>1.65</td>
<td>0.08</td>
<td>69.36</td>
</tr>
<tr>
<td>12:20:01 AM</td>
<td>26.54</td>
<td>0.00</td>
<td>1.64</td>
<td>0.08</td>
<td>71.74</td>
</tr>
<tr>
<td>12:30:01 AM</td>
<td>29.73</td>
<td>0.00</td>
<td>1.66</td>
<td>0.09</td>
<td>68.52</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
var index = $(this).index();
$(".defaultTable tr").each(function() {
//remove body
$(this).find("td:eq("+index+")").remove();
//and head
$(this).find("th:eq("+index+")").remove();
});
DEMO
You could try by getting column number from table
$('.removeMe').click(function(){
var colNum = $(this).parent().children().index($(this));// getting the column number
console.log(colNum);
$(".defaultTable tbody tr").each(function() {
$(this).find("td:eq("+colNum+")").remove();
});
});
Adding mine in with the lot of answers:
Working Example:
http://jsfiddle.net/Twisty/h0asbe6o/
jQuery
function removeColumn(n, o) {
o = (o != "undefined") ? o : $("#testTable1");
console.log("Removing Column '" + o.find("thead tr th:eq(" + n + ")").text() + "' (" + n + ") from " + o.attr("id"));
o.find("tr").each(function(k, e) {
$(e).find("th:eq(" + n + ")").empty().remove();
$(e).find("td:eq(" + n + ")").empty().remove();
});
return true;
}
Also you'd want to fix a few creation issues:
$(document).ready(function() {
$('.defaultTable').dragtable();
$('#test1').click(function() {
$("#testTable1 > thead > tr").append('<th>New Column</th>');
$("#testTable1 > tbody > tr").each(function(key, el) {
if (key == 0) {
var rm = $("<span>", {
class: "removeMe"
})
.html("[X]")
.click(function() {
removeColumn($(this).index());
$(this).remove();
});
rm.appendTo(el);
} else {
$(el).append('<td>New cell in the column</td>');
}
});
$('.defaultTable').removeData().dragtable();
});
$('.removeMe').on("click", function() {
removeColumn($(this).index());
$('.defaultTable').removeData().dragtable();
});
});
This will create new columns properly and allow you to delete either static or dynamically created elements.
EDIT
If you felt like improving the UI, you could do something like this:
http://jsfiddle.net/Twisty/h0asbe6o/4/
HTML
<div class="sample">
<button type="button" id="test1">Add column</button>
<div class="demo">
<h4>demo</h4>
<div class="demo-content">
<table class="defaultTable sar-table" id="testTable1">
<thead>
<tr>
<th><span class="cTitle handle">TIME</span><span class="removeMe">[x]</span></th>
<th><span class="cTitle handle">%user</span><span class="removeMe">[x]</span></th>
<th><span class="cTitle handle">%nice</span><span class="removeMe">[x]</span></th>
<th><span class="cTitle handle">%system</span><span class="removeMe">[x]</span></th>
<th><span class="cTitle handle">%iowait</span><span class="removeMe">[x]</span></th>
<th><span class="cTitle handle">%idle</span><span class="removeMe">[x]</span></th>
</tr>
</thead>
<tbody>
<tr>
<td>12:10:01 AM</td>
<td>28.86</td>
<td>0.04</td>
<td>1.65</td>
<td>0.08</td>
<td>69.36</td>
</tr>
<tr>
<td>12:20:01 AM</td>
<td>26.54</td>
<td>0.00</td>
<td>1.64</td>
<td>0.08</td>
<td>71.74</td>
</tr>
<tr>
<td>12:30:01 AM</td>
<td>29.73</td>
<td>0.00</td>
<td>1.66</td>
<td>0.09</td>
<td>68.52</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
CSS
.removeMe {
font-size: .65em;
float: right;
cursor: pointer;
margin-top: -0.5em;
color: #aaa;
}
.removeMe:hover {
color: #222;
}
jQuery
function removeColumn(n, o) {
o = (o != "undefined") ? o : $("#testTable1");
o.find("tr").each(function(k, e) {
if (k == 0) {
$(e).find("th").eq(n).hide("slow").remove();
} else {
$(e).find("td").eq(n).hide("slow").remove();;
}
});
return true;
}
var dragOptions = {
dragHandle: '.handle'
};
$(document).ready(function() {
$('.defaultTable').dragtable(dragOptions);
$('#test1').click(function() {
var head = $("<th>").html("<span class='cTitle handle'>New Column</span>");
var rm = $("<span>", {
class: "removeMe"
})
.html("[X]")
.click(function() {
removeColumn($(this).parent().index());
$(this).remove();
});
rm.appendTo(head);
head.appendTo("#testTable1 > thead > tr");
$("#testTable1 > tbody > tr").each(function(key, el) {
$(el).append('<td>New Cell</td>');
});
$('.defaultTable').removeData().dragtable(dragOptions);
});
$('.removeMe').on("click", function() {
removeColumn($(this).parent().index());
$('.defaultTable').removeData().dragtable(dragOptions);
});
});
I have this table:
<table border="1">
<tr>
<td></td>
<td>Banana</td>
<td>Orange</td>
<td>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td>2:1</td>
<td>1:1</td>
<td>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td>1:3</td>
<td>2:1</td>
<td>1:1</td>
</tr>
and CSS:
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
What I want to do, is when I for example point my mouse on 1:3 table cell, it should highlight together with Banana and Plum cells.
Any easy way to do it?
Here's fiddle:
http://jsfiddle.net/CZEJT/
If you dont mind a bit of Javascript in there to ensure compatibility, take a look at this JSFiddle
HTML:
<table>
<tr>
<th></th><th>50kg</th><th>55kg</th><th>60kg</th><th>65kg</th><th>70kg</th>
</tr>
<tr>
<th>160cm</th><td>20</td><td>21</td><td>23</td><td>25</td><td>27</td>
</tr>
<tr>
<th>165cm</th><td>18</td><td>20</td><td>22</td><td>24</td><td>26</td>
</tr>
<tr>
<th>170cm</th><td>17</td><td>19</td><td>21</td><td>23</td><td>25</td>
</tr>
<tr>
<th>175cm</th><td>16</td><td>18</td><td>20</td><td>22</td><td>24</td>
</tr>
</table>
CSS:
table {
border-spacing: 0;
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th, .ff-fix {
cursor: pointer;
padding: 10px;
position: relative;
}
td:hover::after,
.ff-fix:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
tr:hover{
background-color: #ffa;
}
}
JS:
function firefoxFix() {
if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {
var tds = document.getElementsByTagName( 'td' );
for( var index = 0; index < tds.length; index++ ) {
tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';
};
var style = '<style>'
+ 'td { padding: 0 !important; }'
+ 'td:hover::before, td:hover::after { background-color: transparent !important; }'
+ '</style>';
document.head.insertAdjacentHTML( 'beforeEnd', style );
};
};
firefoxFix();
below is an example from one of my sites (css):
/*when hover over shape 5 dim shape 5*/
#shape5{
opacity:1.0;
filter:alpha(opacity=100);}
#shape5:hover{
opacity:0.4;
filter:alpha(opacity=40);}
/*When hoverover text5 dim shape 5!*/
#text5:hover + #shape5{opacity:0.4;
filter:alpha(opacity=40);}
Hope that helps!!
Oh Also view: How to affect other elements when a div is hovered
would you like something like this?
unfortunately it would be necessary some javascript
HTML
<table border="1">
<tr>
<td></td>
<td id='1'>Banana</td>
<td id='2'>Orange</td>
<td id='3'>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td class='o1'>1:1</td>
<td class='o2'>1:2</td>
<td class='o3'>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td class='o1'>2:1</td>
<td class='o2'>1:1</td>
<td class='o3'>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td class='o1'>1:3</td>
<td class='o2'>2:1</td>
<td class='o3'>1:1</td>
</tr>
</table>
JAVASCRIPT
var cells1 = $('.o1');
cells1.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#1').css({background: '#ddd'})
})
cells1.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#1').css({background: 'none'})
})
var cells2 = $('.o2');
cells2.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#2').css({background: '#ddd'})
})
cells2.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#2').css({background: 'none'})
})
var cells3 = $('.o3');
cells3.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#3').css({background: '#ddd'})
})
cells3.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#3').css({background: 'none'})
})
CSS
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
Try this:
Fiddle
Without changing your html structure or adding any third party library:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
var elem = document.getElementsByTagName('td')[i];
elem.addEventListener('mouseover', function () {
var text = this.innerHTML;
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
if (elem2.innerHTML == text) {
elem2.style.background = 'red';
}
}
}, false);
elem.addEventListener('mouseout', function () {
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
var text = this.innerHTML;
if (elem2.innerHTML == text) {
elem2.style.background = 'none';
}
}
}, false);
}
}, false);
</script>
I apologise that my answer is only in pseudo code, however I would approach this problem by using javascript (most possibly Jquery). I hope this makes sense...
<table id="tbl"> - so I would give the table an ID
<td onHover="changeHeaderColummns(this)"></td> - then on each of the columns have a jsMethod that fires.
<script>
changeHeaderColumsn(col)
{
var colIndex = col.Index; //get the current column index
var row = GetHeaderRow(); // get the header row
highLightColumn(row, colIndex); //change the colour of the cell
//with the same index in the header
row = getCurrentRow(col.RowIndex); //now get the current row
highlightColumn(row, 0); //change the colour of the cell
//with the index of 0
}
getHeaderRow()
{
return getRow(0);
}
getRow(rowIndex)
{
var table = document.getElementByID("tbl);
return table.rows[rowIndex];
}
highlightColumn(row, colIndex)
{
row[colIndex].style.backgroundcolor = "red";
}
for highlight columns you must use js like this jsfiddler. It's work with jQuery ;)
With code
Using jquery
fiddle: http://jsfiddle.net/itsmikem/CZEJT/12/
Option 1: highlights the cell and just the named fruit cells
$("td").on({
"mouseenter":function(){
$(this).closest("tr").find("td:first-child").css("background","#f99");
var col = $(this).index();
$(this).closest("table").find("tr:first-child").find(String("td:nth-child(" + (col + 1) + ")")).css("background","#f99");
$(this).css("background","#f00");
},
"mouseleave":function(){
$(this).closest("table").find("td,tr").css("background","none");
}
});
Option 2: highlights entire rows and columns that intersect the hovered cell
$("td").on({
"mouseenter": function () {
$(this).closest("tr").css("background", "#f99");
var col = $(this).index();
var myTable = $(this).closest("table");
var rows = $(myTable).find("tr");
$(rows).each(function (ind, elem) {
var sel = String("td:nth-child(" + (col + 1) + ")");
$(this).find(sel).css("background", "#f99");
});
$(this).css("background", "#f00");
},
"mouseleave": function () {
$(this).closest("table").find("td,tr").css("background", "none");
}
});
Currently when the mouse is dragged over a cell, the code below will highlight permissible cells to drag the selected piece to.
I need to modify the code to include clicking as well. For example, when the mouse is dragged over a cell, permissible cells are highlighted. When the same cell is clicked the permissible cells will remain highlighted until either the original cell is clicked again or until one of the highlighted locations is click where upon the image will appear. How can I do this?
Thanks.
Current fiddle.
HTML:
<table border="1" id="tbl">
<tr>
<td ></td>
<td bgcolor=#000000 ></td>
<td class="items p1 p3"><img src="http://icons.iconarchive.com/icons/deleket/soft- scraps/32/Button-Blank-Red-icon.png"/></td>
</tr>
<tr>
<td bgcolor=#000000 ></td>
<td class="items p1"></td>
<td class="items p3" bgcolor=#000000 ></td>
</tr>
<tr>
<td class="piece" id="p1" ><img src="http://icons.iconarchive.com/icons/deleket/soft-scraps/32/Button-Blank-Gray-icon.png"></td>
<td bgcolor=#000000 ></td>
<td class="piece" id="p3" ><img src="http://icons.iconarchive.com/icons/deleket/soft-scraps/32/Button-Blank-Gray-icon.png" ></td>
</tr>
</table>
jQuery:
$('img').draggable({ });
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
if ($(this).css("background-color")==='rgb(255, 255, 0)') {
$(this).children('img').remove();
var cell = ui.draggable.appendTo($(this)).css({
'left': '0',
'top': '0'
});
$('img').draggable('disable');
} else {
ui.draggable.draggable('option','revert',true);
}
$("td").each(function() {
var id = $(this).attr("id");
$("."+id).css("background", "");
});
}
});
$(".piece").mouseover(function() {
id = $(this).attr('id');
$("."+id).css("background", "yellow");
}).mouseleave(function() {
id = $(this).attr('id');
$("."+id).css("background", "");
});
I think this adds the functionality you're looking for:
jsFiddle
JS
var imgs = $('img');
imgs.draggable({ });
$('#tbl td').droppable({
hoverClass: 'over',
drop: function(event, ui) {
var cell = $(this);
var img = ui.draggable;
if (cell.hasClass("yellow")) {
cell.children('img').remove();
img.appendTo(cell).css({
'left': '0',
'top': '0'
});
img.draggable('disable');
} else {
img.draggable('option','revert',true);
}
$('.yellow').removeClass('yellow');
setUpHover();
}
});
imgs.click(function(){
//the image we just clicked on
var img = $(this);
//The cells we can move our image to.
var cells = $("." + img.parent().attr('id'));
//disable dragging of other images while this one is in focus
imgs.not(img).draggable('disable');
//disable the hover event so that we don't lose our highlighted cells
imgs.unbind('hover');
//add a dynamic click event to the cells we're allowed to click on.
cells.click(function(){
//re-enable dragging for all images
imgs.draggable('enable');
//remove the dynamic click event and remove the yellow background
cells.unbind('click').removeClass('yellow');
//add the image to the cell.
$(this).html(img);
//re-bind the hover event.
setUpHover();
});
});
function setUpHover(){
imgs.unbind('hover').hover(function() {
var id = $(this).parent().attr('id');
$("."+id).addClass("yellow");
}, function() {
var id = $(this).parent().attr('id');
$("."+id).removeClass("yellow");
});
}
setUpHover();
CSS
#tbl td { width:32px; height:32px;}
.over { background-color: red; }
.yellow {
background-color:yellow !important;
}