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);
});
});
Related
I have implemented a checkall checkbox for the table but the table has pagination and DOM only gets the elements currently showing on the page. my implementation is not working on other paginations. how can we achieve this task?
.cshtml code
<table id="instruments" class="table table-bordered table-striped table-condensed table-hover smart-form has-tickbox" style="width: 100%;">
<thead>
<tr>
<th>
<input id="chkAffectCheckboxGroup" type="checkbox" />
</th>
<th data-class="expand" style="white-space: nowrap">#Model.idResource</th>
<th data-hide="phone" style="white-space: nowrap">#Model.SResource</th>
<th data-hide="phone" style="white-space: nowrap">#Model.LocationResource</th>
</tr>
</thead>
<tbody>
#for (int i = 0; i < Model.Instruments.Count; i++)
{
var values = Model.Instruments[i].Value.Split('~');
var status = values.Length > 0 ? values[0] : "";
var location = values.Length > 1 ? values[1] : "";
<tr>
<td>
<label class="checkbox">
#Html.CheckBoxFor(m => m.Instruments[i].Selected, new { #class = "chkInst" })
<i></i>
</label>
</td>
<td><label>#Model.Instruments[i].Text</label></td>
<td><label>#status</label></td>
<td><label>#location</label></td>
</tr>
}
</tbody>
</table>
Jquery Code
$(document).ready(
console.log("jquery called"),
manageCheckboxGroup('chkAffectCheckboxGroup', 'chkInst')
);
JavaScript Code
function manageCheckboxGroup(masterCheckboxId, slaveCheckboxesClass) {
$("#" + masterCheckboxId).click(function () {
$("." + slaveCheckboxesClass).prop('checked', this.checked);
});
$("." + slaveCheckboxesClass).click(function () {
if (!this.checked) {
$("#" + masterCheckboxId).prop('checked', false);
}
else if ($("." + slaveCheckboxesClass).length == $("." + slaveCheckboxesClass + ":checked").length) {
$("#" + masterCheckboxId).prop('checked', true);
}
});
}
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 have the following table
<table class="hTab">
<tr class="hTr"> </tr>
<tr class="hTr"> </tr>
<tr class="hTr"> </tr>
</table>
<tr> <input type=button value="Show 1 more" id="onemore" /></tr>
I have used following jQuery code to show the rows one by one (I have declared 10 rows in the table)
var currentrow = 0;
$('#hTab #hTr').hide();
$('#hTab #tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('#hTab #hTr:eq(' + currentrow + ')').show();
});
But at the moment it's not working. If anyone can show me the error in my code, it will be very helpful
You should use class selector . instead of id selector #, e.g :
$('.hTab .hTr:eq(' + currentrow + ')').show();
So the code will be :
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
NOTE : the button shouldn't be inside tr tag because it's outside of the table, and you have to add tds inside every tr.
Hope this helps.
var currentrow=0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="hTab">
<tr class="hTr"><td> A </td></tr>
<tr class="hTr"><td> B </td></tr>
<tr class="hTr"><td> C </td></tr>
</table>
<input type=button value="Show 1 more" id="onemore" />
hTab and hTr is class not a id:
so use everywhere:
$('.hTab .hTr')
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab .hTr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="hTab">
<tr class="hTr"> <td>A<td> </tr>
<tr class="hTr"> <td>B<td> </tr>
<tr class="hTr"> <td>C<td> </tr>
</table>
<tr> <input type=button value="Show 1 more" id="onemore" /></tr>
please see the fiddle link
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
I have created a jquery function that allows me to click on the UP arrow and it swaps rows in a table. I have rank numbers in each row. But I can only get the clicked number to change. I want both numbers to swap. I know it is something with getting the value in abovecnt. I just can't figure out how to get that value of the row above. Right now it is just undefined.
http://jsfiddle.net/Thread7/2rmowem4/15/
$('.change-rank').click(function() {
var cnt = $(this).attr('cnt');
var direction = $(this).attr('data-direction'),
$original = $(this).closest("tr"),
$target = direction === "up" ? $original.prev() : $original.next();
if ( $target.length && direction === "up" ) {
$original.insertBefore($target);
abovecnt = $original.find('.ranky input[type="text"]').val();
$('#rank_' + cnt).val(cnt-1);
$('#rank_' + abovecnt).val(cnt);
alert('abovecnt=' + abovecnt + '|cnt=' + cnt);
}
else if( $target.length ) {
$original.insertAfter($target);
}
});
Note: I'll eventually want the down arrow to swap also, but right now just trying to get it to work.
I converted your cnt attributes to data attributes for this.
EDIT: updated JS snippet to #tripleb 's recommendation: before and after .. as opposed to doing inserts and changing values of the arrows.
Sample Code Snippet
$('.change-rank.up').click(function(ev) {
var $original = $(this).closest("tr"),
$target = $original.prev();
if ($target.length) {
var cnt = $original.data('cnt'),
targetcnt = $target.data("cnt");
if (targetcnt) {
$original.after($target);
alert(targetcnt);
}
}
});
$('.change-rank.down').click(function(ev) {
var $original = $(this).closest("tr"),
$target = $original.next();
if ($target.length) {
var cnt = $original.data('cnt'),
targetcnt = $target.data("cnt");
if (targetcnt) {
$original.before($target);
alert(targetcnt);
}
}
});
.change-rank.up:after {
content: attr(data-icon);
}
.change-rank.down:after {
content: attr(data-icon);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Rank</td>
<td>Username</td>
</tr>
<tr data-cnt='1'>
<td>
1</td>
<td>Joey</td>
<td>
<input type='text' id='rank_1' class='ranky' value='1' />
</td>
</tr>
<tr data-cnt='2'>
<td>
2</td>
<td>Randy</td>
<td>
<input type='text' id='rank_2' class='ranky' value='2'>
</td>
</tr>
<tr data-cnt='3'>
<td>
3</td>
<td>Bobby</td>
<td>
<input type='text' id='rank_3' class='ranky' value='3' />
</td>
</tr>
<tr data-cnt='4'>
<td>
4</td>
<td>Jesse</td>
<td>
<input type='text' id='rank_4' class='ranky' value='4' />
</td>
</tr>
</table>
JsFiddle: Example
why not this:
if ( $target.length && direction === "up" ) {
$original.after($target)
}
else if( $target.length ) {
$original.before($target);
}
http://jsfiddle.net/2rmowem4/16/
I'm new to jQuery and JavaScript. I'm trying to click on my Edit button in my table and make the entire row editable. For some reason it's not working. I think it's only looking at the cell the edit button is in, but I'm not sure how to make it change the entire row to be editable (except the edit button field). I tried moving contenteditable to the tr tag level from the td tag level but it didn't fix it. I was looking at this link as an example, but I think there's something I'm missing. Here is what my code looks like:
<head>
<title></title>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnHide').click(function() {
//$('td:nth-child(2)').hide();
// if your table has header(th), use this
$('td:nth-child(3),th:nth-child(3)').hide();
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.editbtn').click(function(){
$(this).html($(this).html() == 'Edit' ? 'Save' : 'Edit');
if('td[contenteditable=true]')) {
'td[contenteditable=false]');
}
else if('td[contenteditable=false]')){
'td[contenteditable=true]');
}
//else not editable row
}); //moved this
});
</script>
</head>
<body>
<table id="tableone" border="1">
<thead>
<tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th><th class="col3">Header 4</th></tr>
</thead>
<tr class="del">
<td contenteditable="false">Row 0 Column 0</td> //changed to false after experiment
<td><button class="editbtn">Edit</button></td>
<td contenteditable="false">Row 0 Column 1</td>
<td contenteditable="false">Row 0 Column 2</td>
</tr>
<tr class="del">
<td contenteditable="false">Row 1 Column 0</td>
<td><button class="editbtn">Edit</button></td>
<td contenteditable="false">Row 1 Column 1</td>
<td contenteditable="false">Row 1 Column 2</td>
</tr>
</table>
<input id="btnHide" type="button" value="Hide Column 2"/>
</body>
Your code with the button click is too complicated. I have reduced it by making it easier to understand.
$(document).ready(function () {
$('.editbtn').click(function () {
var currentTD = $(this).parents('tr').find('td');
if ($(this).html() == 'Edit') {
$.each(currentTD, function () {
$(this).prop('contenteditable', true)
});
} else {
$.each(currentTD, function () {
$(this).prop('contenteditable', false)
});
}
$(this).html($(this).html() == 'Edit' ? 'Save' : 'Edit')
});
});
Code Explained:
1) Get all the tds within tr using below code
var currentTD = $(this).parents('tr').find('td');
2) Then as usual iterate through each tds and change its contenteditable property like below
$.each(currentTD, function () {
$(this).prop('contenteditable', true)
});
Updated JSFiddle
Try this:
$('.editbtn').click(function() {
var $this = $(this);
var tds = $this.closest('tr').find('td').filter(function() {
return $(this).find('.editbtn').length === 0;
});
if ($this.html() === 'Edit') {
$this.html('Save');
tds.prop('contenteditable', true);
} else {
$this.html('Edit');
tds.prop('contenteditable', false);
}
});
jsFiddle
Try this. I created right now.
I hope this can help.
jQuery(document).ready(function() {
$('#edit').click(function () {
var currentTD = $(this).closest('tr');
if ($(this).html() == 'Edit') {
$(currentTD).find('.inputDisabled').prop("disabled",false);
} else {
$(currentTD).find('.inputDisabled').prop("disabled",true);
}
$(this).html($(this).html() == 'Edit' ? 'Save' : 'Edit')
});
});
https://jsfiddle.net/mkqLdo34/1/