Remove row from appended table when checkbox is unchecked - javascript

I'm a beginner and know only basics of javascript and MVC. Now I need to remove the corresponding row from the appended table whenever the row is unchecked..
This is my table ...
<table id="sortabletable" class="tab sortable">
<tr class = trow>
<td>
#Html.DisplayFor(modelItem => item.AId)
</td>
<td>
#Html.DisplayFor(modelItem => item.UId)
</td>
<td><input type="checkbox" name="thecheckbox" value="#item.TXId" class ="cbox" checked/></td>
</tr>
</table>
<table class="tab" id="tlist">
<tbody>
</tbody>
</table>
and here's my Jquery
$(function () {
$('input[type="checkbox"]').click(function () {
_this = $(this);
if ($(this).is(':checked')) {
row.find('td:nth-child(1), td:nth-child(3)').hide();
var row = _this.closest("tr").clone();
$('#tlist').append(row);
} else {
// i dont know
}
});
});
I don't know how to select the row based on checked value from an appended table.

use a combination of closest and remove
$('input.cbox').on('change', function() {
var _this = $(this);
if(this.checked) {
var row = _this.closest("tr").clone();
row.find('td:nth-child(1), td:nth-child(3)').hide();
row.data('id' , this.value);
$('#tlist').append(row);
}
else {
$('[data-id="'+ this.id +'"]', '#tlist').remove()
}
});

Related

How can I adapt the following datatable script code which uses checkbox all to my asp.net core app?

Recently, I installed the Datatable library in my Asp.net app, and is very useful!
I wanted one of my Datatables to have a "Checkbox all" that when pressed, would mark all the existing checkboxes in the current rows of the table which are filtered, and aslo I wanted that all of those checkboxes were part of a group with a name attribute assigned. And when searching, I found a already-made Script that does just what I want!
This one: https://jsfiddle.net/gyrocode/abhbs4x8/
but I'm having a hard time trying to understand how the heck I should adapt this script to my app environment. Since I use a Model instead of ajax/json?, and unlike the link code, I want to put a checkbox manually in each td row of my table, instead of making them appear in an empty "td", as the link code does (thing I don't understand exactly how the code does it).
Can someone help me adapt the code made by gyrocode too my app? Thank you very much in advance.
My view code without gyrocode's jquery datable script:
#model IEnumerable<Co.Models.Com>
<div class="container">
<div class="card level-3">
<h3>List</h3>
<link rel="stylesheet" type="text/css" href="~/DataTables/datatables.min.css" />
<div>
<table class="table table-sm table-bordered select" id="tabla">
<thead class="thead-dark">
<tr>
<th><input name="select_all" value="1" type="checkbox"></th>
<th>
<div>Nomb</div>
</th>
<th>
<div>Fech</div>
</th>
<th>
<div>AAA</div>
</th>
<th>
<div>Tuuu</div>
</th>
<th>
<div>Hor</div>
</th>
<th>
<div>Mino</div>
</th>
<th><div></div></th>
<th>
</th>
<th><div></div></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td><input name="group" value=#item.Id type="checkbox">
</td>
<td>
#Html.DisplayFor(modelItem => item.Nom)
</td>
<td>
#Html.DisplayFor(modelItem => item.Fech)
</td>
<td>
#Html.DisplayFor(modelItem => item.Aombr)
</td>
<td>
#Html.DisplayFor(modelItem => item.Tip)
</td>
<td>
#Html.DisplayFor(modelItem => item.Hor)
</td>
<td>
#Html.DisplayFor(modelItem => item.Tooo)
</td>
<td>
<a class="btn btn-sm btn-primary" asp-action="Edit" asp-route-id="#item.Id">
EDIT
</a>
</td>
<td>
<a class="btn btn-sm btn-primary" asp-action="Details" asp-route-id="#item.Id">
DETAILS
</a>
</td>
<td>
<a class="btn btn-sm btn-danger" asp-action="Delete" asp-route-id="#item.Id">
DELETE
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
<script src="~/assets/js/jquery.min.js"></script>
<script type="text/javascript" src="~/DataTables/datatables.min.js"></script>
<script>
$("#tabla").dataTable({
responsive: true,
buttons: [
'excelHtml5',
'csvHtml5',
'pdfHtml5'
],
});
</scrip>
Jquery Datatable: https://datatables.net/download/
(PD: yes, I tried to just change my table Id from "tabla" to "example", but that wasn't enough to make the code work)
For how to apply gyrocode's code to your code,you could check the following code.And be sure change $("#tabla").dataTable({}) to $("#tabla").DataTable({}):
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
function updateDataTableSelectAllCtrl(table) {
var $table = table.table().node();
var $chkbox_all = $('tbody input[type="checkbox"]', $table);
var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);
// If none of the checkboxes are checked
if ($chkbox_checked.length === 0) {
chkbox_select_all.checked = false;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If all of the checkboxes are checked
} else if ($chkbox_checked.length === $chkbox_all.length) {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If some of the checkboxes are checked
} else {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = true;
}
}
}
$(document).ready(function () {
// Array holding selected row IDs
var rows_selected = [];
var table = $("#tabla").DataTable({
responsive: true,
buttons: [
'excelHtml5',
'csvHtml5',
'pdfHtml5'
],
});
// Handle click on checkbox
$('#tabla tbody').on('click', 'input[type="checkbox"]', function (e) {
var $row = $(this).closest('tr');
// Get row data
var data = table.row($row).data();
// Get row ID
var rowId = data[0];
// Determine whether row ID is in the list of selected row IDs
var index = $.inArray(rowId, rows_selected);
// If checkbox is checked and row ID is not in list of selected row IDs
if (this.checked && index === -1) {
rows_selected.push(rowId);
// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
} else if (!this.checked && index !== -1) {
rows_selected.splice(index, 1);
}
if (this.checked) {
$row.addClass('selected');
} else {
$row.removeClass('selected');
}
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle click on table cells with checkboxes
$('#tabla').on('click', 'tbody td, thead th:first-child', function (e) {
$(this).parent().find('input[type="checkbox"]').trigger('click');
});
// Handle click on "Select all" control
$('thead input[name="select_all"]', table.table().container()).on('click', function (e) {
if (this.checked) {
$('#tabla tbody input[type="checkbox"]:not(:checked)').trigger('click');
} else {
$('#tabla tbody input[type="checkbox"]:checked').trigger('click');
}
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle table draw event
table.on('draw', function () {
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
});
});
</script>

Unmark checkbox when there is no more TR and TABLE goes hide

I'm working on this function for remove any marked checkbox in a selector container element. The code works fine but has a small problem: I'm not able to uncheck the first checkbox (the one that toggle all the checkboxes in a selector2 container). Now this is the code for remove the checked checkboxes:
function eliminarMarcados(selector, toggleMsg, msgSelector) {
$(selector + " input[type='checkbox']:checked").closest("tr").not('.tableHead').remove();
if (toggleMsg) {
if ($(selector + " tbody tr").length == 0) {
$(msgSelector).show();
$(selector).hide();
// 1st test didn't work since it's not right
//$(selector + " tr").hasClass('tableHead').$(selector + " input[type='checkbox']").prop('checked', false);
}
}
}
And this is how I call it:
$("#btnEliminarNorma").on('click', function () {
eliminarMarcados("#tablaNorma", true, "#alertSinNorma");
});
This is the code I'm using for toggle all checkboxes checked:
function marcarTodosCheck(selChk, tableBody) {
$(selChk).on('click', function () {
var $toggle = $(this).is(':checked');
$(tableBody).find("input:checkbox").prop("checked", $toggle).trigger("change");
});
$(tableBody).find("input:checkbox").on('click', function () {
if (!$(this).is(':checked')) {
$(selChk).prop("checked", false).trigger("change");
} else if ($(tableBody).find("input:checkbox").length == $(tableBody).find("input:checkbox:checked").length) {
$(selChk).prop("checked", true).trigger("change");
}
});
}
And I call it as follow:
marcarTodosCheck("#toggleCheckNorma", "#tablaNorma");
And this is the HTML code behind this:
<table class="table table-condensed" id="tablaNorma">
<thead>
<tr class="tableHead">
<th><input type="checkbox" id="toggleCheckNorma" name="toggleCheckNorma"></th>
<th>Nro.</th>
<th>Norma COVENIN</th>
<th>Año de Publicación</th>
<th>Comité Técnico</th>
</tr>
</thead>
<tbody id="normaBody">
<tr class="">
<td><input type="checkbox" value="5"></td>
<td>382</td><td>Sit alias sit.</td>
<td>1970</td><td>Velit eum.</td>
</tr>
<tr class="">
<td><input type="checkbox" value="6"></td>
<td>38362</td>
<td>Et voluptatem.</td><td>1976</td>
<td>Et voluptatem.</td>
</tr>
</tbody>
</table>
How I can unmark the first checkbox?
I've just made a Fiddle with an additional <button id="btnEliminarNorma">Uncheck</button> to remove the checkmarks and the adjustment of your first approach in the function eliminarMarcados() :
$(selector).find(" input[type='checkbox']").prop('checked', false);

Select data attribute from row only for rows with checked checkboxes

I have table has 2 columns: checkbox and name.
<table id="data">
<tr class="header">
<th>
<input type="checkbox" class="download" />
</th>
<th>Name</th>
</tr>
<tr data-id="1">
<td>
<input type="checkbox" class="download" />
</td>
<td>One</td>
</tr>
<tr data-id="2">
<td>
<input type="checkbox" class="download" />
</td>
<td>Two</td>
</tr>
<tr data-id="3">
<td>
<input type="checkbox" class="download" />
</td>
<td>Something</td>
</tr>
</table>
I would like to select data attribute from those rows that have checkbox selected. Right now I'm doing it this way:
$(document).on('click', "#select", function (e) {
var mydata=[];
$.each($('#data tbody tr:not(.header)'), function(i, row) {
if($(row).find('input[type=checkbox]').is(":checked"))
mydata.push($(row).data('id'));
});
console.log(mydata);
});
This works fine, but can this be done better/faster?
Here is my working demo: http://jsfiddle.net/Misiu/yytR2/2/
Also how can I uncheck checkbox in header when one of more checkboxes in body are unchecked and check it when all will get checked?
EDIT: My final working code (thanks to #tymeJV):
$(document).on('change', "#data tr.header input.download", function (e) {
$('#data tbody tr:not(.header) input.download').prop('checked', $(this).is(":checked"));
});
$(document).on('change', "#data tr:not(.header) input.download", function (e) {
if ($(this).is(":checked") && $('#data tr:not(.header) input.download:not(:checked)').length == 0) {
$('#data tbody tr.header input.download').prop('checked', true);
} else {
$('#data tbody tr.header input.download').prop('checked', false);
}
});
$(document).on('click', "#select", function (e) {
var rows = $("#data tr:not(.header) td input:checked").map(function () {
return $(this).closest("tr").data("id");
}).get();
console.log(rows);
});
You can do:
var rows = $("#data tr:not(.header) td input:checked").map(function() {
return $(this).closest("tr").data("id");
}).get();
It iterates yet, but only checked rows.
You can use:
$(".download:checkbox").map(function() {
return $(this).parents('tr').data('id');
}).get()

getting the row values with checkbox

hello guys? can you please help with this? i have this tables in HTML.what i want to achieve is that, when i click the row the checkbox will be checked and the row will be highlighted.and is it possible with the checkbox column hidden?
<table border="1" id="estTable">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>Chris</td>
<td>10</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>Cass</td>
<td>15</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>Aldrin</td>
<td>16</td>
</tr>
</tbody>
</table>
<input type="button" value="Edit" id="editbtn"/>
<div id="out"></div>
and i have this javascript to get the values of the selected row.And i was hoping to print one row at a time.
$('#editbtn').click(function(){
$('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
$('#out').append("<p>"+$(this).text()+"</p>");
});
});
This gets a little easier when you use classes to add more context to your source:
<tr>
<td class="select hidden">
<input type="checkbox">
</td>
<td class="name">Chris</td>
<td class="age">10</td>
</tr>
Then you can do something like this:
$(document).ready(function () {
'use strict';
$('#estTable tbody tr').click(function (e) {
//when the row is clicked...
var self = $(this), //cache this
checkbox = self.find('.select > input[type=checkbox]'), //get the checkbox
isChecked = checkbox.prop('checked'); //and the current state
if (!isChecked) {
//about to be checked so clear all other selections
$('#estTable .select > input[type=checkbox]').prop('checked', false).parents('tr').removeClass('selected');
}
checkbox.prop('checked', !isChecked).parents('tr').addClass('selected'); //toggle current state
});
$('#editbtn').click(function (e) {
var selectedRow = $('#estTable .select :checked'),
tr = selectedRow.parents('tr'), //get the parent row
name = tr.find('.name').text(), //get the name
age = parseInt(tr.find('.age').text(), 10), //get the age and convert to int
p = $('<p />'); //create a p element
$('#out').append(p.clone().text(name + ': ' + age));
});
});
Live demo: http://jsfiddle.net/Lf9rf/
if i understand the "print one row at a time" correctly, i think you need to empty your "out" selector before executing the new call
$('#editbtn').click(function(){
$('#out').empty();
$('#estTable tr').filter(':has(:checkbox:checked)').find('td').each(function() {
$('#out').append("<p>"+$(this).text()+"</p>");
});
});
jsBin demo
CSS:
.highlight{
background:gold;
}
jQuery:
$('#estTable tr:gt(0)').click(function( e ){
var isChecked = $(this).find(':checkbox').is(':checked');
if(e.target.tagName !== 'INPUT'){
$(this).find(':checkbox').prop('checked', !isChecked);
}
$(this).toggleClass('highlight');
});

enable disable textbox inside a table when checkbox checked

I am using jQuery. How to enable or disable textbox inside a table when checkbox checked.
This is my edit.cshtml.
<table id="scDetails" class="dataTable">
<thead>
<tr>
<th>RItem</th>
<th>IChecked</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
#foreach (var fback in Model.Fbacks)
{
<tr>
<td #Html.DisplayFor(m => fback.RItem)</td>
<td>#Html.CheckBoxFor(m => fback.IChecked)</td>
<td>#Html.TextBoxFor(m => fback.Notes)</td>
</tr>
}
</tbody>
</table>
What i have tried is:
$('td :checkbox').change(function () {
var parentTx = $(this).closest('tr').find(input[type = "text"]);
if (this.checked) {
parentTx.attr("disabled",false);
} else {
parentTx.attr("disabled", true);
}
});
Where am doing wrong? I dont want to use any classes on the controls to achieve this.
You missed the quotes, and you could simply your code with:
$('td input[type="checkbox"]').change(function () {
$(this).closest('tr').find('input[type="text"]').prop('disabled', !this.checked);
}).change();

Categories