Deleting multiple rows in a HTML table using checkbox in javascript - javascript

I can't delete the rows that are selected.
I want to delete the rows checked with checkbox. But I can't access the table rows and check whether the checkbox is checked. What should I do?
Code:
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>edit</th>
</tr>
<tr>
<td><input type="checkbox" id="select"></td>
<td>A1</td>
<td>B1</td>
<td>10</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
<tr>
<td><input type="checkbox" id="select"></td>
<td>A3</td>
<td>B3</td>
<td>30</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
<tr>
<td><input type="checkbox" id="select" class="select"></td>
<td>A2</td>
<td>B2</td>
<td>20</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
</table>
</div>
<button onclick="deleteRow();">Remove</button>
<script>
function deleteRow() {
var table = document.getElementById("table");
var rowCount = table.rows.length;
console.log("rowcount : " + rowCount);
for (var i = 1; i < rowCount; i++) {
var c = table.rows[i].cells[0].childNodes;
console.log(c);
if (c.checked == 1) {
console.log("i :" + i);
table.deleteRow(i);
}
}
}.
</script>

Use querySelectorAll() and :checked to select all checked checkbox.
parentNode.parentNode is to get parent tr node
function deleteRow() {
document.querySelectorAll('#table .select:checked').forEach(e => {
e.parentNode.parentNode.remove()
});
}
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>edit</th>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>A1</td>
<td>B1</td>
<td>10</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>A3</td>
<td>B3</td>
<td>30</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>A2</td>
<td>B2</td>
<td>20</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
</table>
</div>
</div>
<button onclick="deleteRow();">Remove</button>
Note: Avoid using duplicate id

The problem with your code is that after deleting a row, the index of all subsequent rows immediately decreases by one because HTMLTableElement.prototype.rows returns a live HTMLCollection.
That not only leads to your loop executing too often (because you cached table.rows.length), but also to subsequent indexes no longer matching.
I'd suggest using the much more readable for...of loop, which only gets slightly more complicated because tables don't seem to allow for using table.removeChild(row):
function deleteRow() {
const table = document.getElementById("table");
for (const [index, row] of [...table.rows].entries()) {
if (row.querySelector('input:checked')) {
table.deleteRow(index);
}
}
}
<table id="table" border="1">
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>edit</th>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>A1</td>
<td>B1</td>
<td>10</td>
<td><input type="button" value="edit" class="edit"></td>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>A3</td>
<td>B3</td>
<td>30</td>
<td><input type="button" value="edit" class="edit"></td>
</tr>
<tr>
<td><input type="checkbox" class="select"></td>
<td>A2</td>
<td>B2</td>
<td>20</td>
<td><input type="button" value="edit" class="edit"></td>
</tr>
</table>
<button onclick="deleteRow();">Remove</button>

The way you go about deleting the rows is wrong, because you use a for loop with a pre-cached length, but when a row, say i, is deleted then the row i+1 becomes i and the length changes.
A correct way to solve this problem is to use a while loop without caching the number of rows and incrementing the index only when you don't delete a row.
Example:
function deleteRow () {
/* Cache the table. */
var table = document.getElementById("table");
/* Create the index used in the loop. */
var index = 1;
/* Repeat as long as the index is less than the number of rows. */
while (index < table.rows.length) {
/* Get the input of the cell. */
var input = table.rows[index].cells[0].children[0];
/* Check whether the input exists and is checked. */
if (input && input.checked) {
/* Delete the row at the current index. */
table.deleteRow(index);
}
else {
/* Increment the index. */
index++;
}
}
}
<div class="container">
<div class="tab tab-1">
<table id="table" border="1">
<tr>
<th></th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>edit</th>
</tr>
<tr>
<td><input type="checkbox" id="select"></td>
<td>A1</td>
<td>B1</td>
<td>10</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
<tr>
<td><input type="checkbox" id="select"></td>
<td>A3</td>
<td>B3</td>
<td>30</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
<tr>
<td><input type="checkbox" id="select" class="select"></td>
<td>A2</td>
<td>B2</td>
<td>20</td>
<td><input type="button" value="edit" id="edit"></td>
</tr>
</table>
</div>
<button onclick="deleteRow();">Remove</button>

Related

How can I filter the column type of the table using two buttons?

I want to filter the type column, one button filters the aquatic and in the other all except the aquatic
<button type="button" onclick="Aquatic()">Aquatic</button>
<button type="button" onclick="NotAquatic()" >everything but aquatic</button>
<table class="table" >
<thead>
<tr>
<th scope="col">Animal</th>
<th scope="col">Type </th>
</tr>
</thead>
<tbody id="" >
<tr>
<td>bat</td>
<td>aerial</td>
</tr>
<tr>
<td>Fish</td>
<td>Aquatic</td>
</tr>
<tr>
<td>Horse</td>
<td>Land</td>
</tr>
<tr>
<td>Shark</td>
<td>Aquatic</td>
</tr>
<tr>
<td>Elephant</td>
<td>Land</td>
</tr>
<tr>
<td>Whale</td>
<td>Aquatic</td>
</tr>
<tr>
<td>dove</td>
<td>aerial</td>
</tr>
</tbody>
</table>
Hopefully this helps point you in the right direction! have a filterTable function which grabs all the table rows, and removes any inline style changes previously added to display. Then, I filter all the trs by the innerHTML content not including the term, and I take all those trs and set their display to none
function filterTable(aquaShown) {
const trs = [...document.querySelectorAll("tbody tr")];
trs.forEach(tr => tr.style.display = "");
const hiddenTrs = aquaShown ?
trs.filter(tr => !tr.innerHTML.includes("Aquatic")) :
trs.filter(tr => tr.innerHTML.includes("Aquatic"));
hiddenTrs.forEach(tr => tr.style.display = "none");
}
function aquatic() {
filterTable(true);
}
function nonaquatic() {
filterTable(false);
}
<button type="button" onclick="aquatic()">Aquatic</button>
<button type="button" onclick="nonaquatic()">Non-Aquatic</button>
<table class="table">
<thead>
<tr>
<th scope="col">Animal</th>
<th scope="col">Type </th>
</tr>
</thead>
<tbody id="">
<tr>
<td>Fish</td>
<td>Aquatic</td>
</tr>
<tr>
<td>Horse</td>
<td>Land</td>
</tr>
<tr>
<td>Shark</td>
<td>Aquatic</td>
</tr>
<tr>
<td>Elephant</td>
<td>Land</td>
</tr>
<tr>
<td>Whale</td>
<td>Aquatic</td>
</tr>
</tbody>
</table>
EDIT refactored based on further clarification in comments

jquery automatically check checkbox with values in array

I have a table like so
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr>
<td>431</td>
<td>Ana</td>
<td>22</td>
<td><input type="checkbox" name="action[]" class="checkboxes" /></td>
</tr>
<tr>
<td>123</td>
<td>tom</td>
<td>21</td>
<td><input type="checkbox" name="action[]" class="checkboxes" /></td>
</tr>
</tbody>
</table>
I have a jquery array where there some ids stored of those rows example
id= [123,431,213]
what I want is when my page loads the ids which are inside the array to be already checked
$(document).ready(function () {
//code
});
I do not know how to go about this any help would be helpful
Iterate over each row in the table body and for each take the text value of the first cell and check to see if your array includes it.
const arr = [ 431, 123, 888 ];
// Iterate over the rows
$('tbody tr').each((i, el) => {
// Grab the first cell's text and coerce it to a number
const number = Number($(el).find('td').first().text());
// If the value is in the array
if (arr.includes(number)) {
// Find the input and check it
$(el).find('input[type="checkbox"]').prop('checked', 'checked');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr>
<td>431</td>
<td>Ana</td>
<td>22</td>
<td><input type="checkbox" name="action[]" class="checkboxes" /></td>
</tr>
<tr>
<td>124</td>
<td>Bob</td>
<td>23</td>
<td><input type="checkbox" name="action[]" class="checkboxes" /></td>
</tr>
<tr>
<td>123</td>
<td>tom</td>
<td>21</td>
<td><input type="checkbox" name="action[]" class="checkboxes" /></td>
</tr>
</tbody>
</table>
var ids = ['431', '132'];
$( document ).ready(function() {
$('td.id').each(function( index ) {
if (ids.includes($(this).text())){
$( "input.checkboxes" ).eq( index ).prop( "checked", true );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>action</th>
</tr>
</thead>
<tbody>
<tr>
<td class="id">431</td>
<td>Ana</td>
<td>22</td>
<td><input type="checkbox" name="action[]" class="checkboxes" /></td>
</tr>
<tr>
<td class="id">123</td>
<td>tom</td>
<td>21</td>
<td><input type="checkbox" name="action[]" class="checkboxes" /></td>
</tr>
</tbody>
</table>

Angualr Datatables: How to get sum of selected column values dynamically using javaScript

Have one table, and if we checkbox checked amount values automatically sum and displayed on top. Tried below code, its getting values but not getting exact sum values. Could you pls suggest the what is the issue..
checkboxCheckCount(info: any): void {
var creditAmount = 0;
$("#firstTable input:checked").each(function() {
alert(info.index);
if (info.index != "") {
creditAmount += parseFloat(info.index);
} else {
creditAmount = creditAmount;
}
});
Stackblitz
As you are already using each loop to iterate through your checked checkboxes you can use $(this).closest("tr").find("td:eq(1)") this will give you amount column td value and then you can pass same to your creditAmount.
Demo Code :
$('input[type="checkbox"]').on('change', function() {
var creditAmount = 0;
$("#firstTable input:checked").each(function() {
//get td(amount column value)
var values = $(this).closest("tr").find("td:eq(1)").text()
if (values != "") {
creditAmount += parseFloat(values);
}
});
$("#idCheckBoxLabel").text(creditAmount);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div>
<div>Count::<span id="idCheckBoxLabel"></span>
<div>
<div>
<table datatable id="firstTable" [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<th><input type="checkbox"></th>
<th>Amount</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>1</td>
<td>Abc</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>2</td>
<td>Abc</td>
<td>xyz</td>
</tr>
<tr>
<td><input type="checkbox" class="checkboxCls" name="id"></td>
<td>3</td>
<td>Abc</td>
<td>xyz</td>
</tr>
</tbody>
</table>
</div>
</div>

How to auto paste a value if checkbox is checked

I want a functionality, i have a list with checkbox i if checkbox is selected i want to paste the selected value in a text field.
Something like appeared in above image.
edited:
<table id="userTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Id</th>
<th>Order Proposed Id</th>
<th>Order Proposed Date</th>
<th>Store Id</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<%for(Order orderSList:orderList){ %>
<tr>
<td><%=orderSList.getOrderId()%></td>
<td><%=orderSList.getOrderProposedId()%></td>
<td><%=orderSList.getOrderProposedDate()%></td>
<td><%=orderSList.getStoreId()%></td>
<td><input type="checkbox" name="<portlet:namespace/>notSubmitList" value="<%=orderSList.getOrderId()%>" class="case" /></td>
</tr>
<%} %>
</tbody>
</table>
<script>
var selectedValue = function(id, _this){
var checkboxes = document.getElementsByClassName('selectedIN');
for (var i = 0; i < checkboxes.length; i++) {
if(_this != checkboxes[i]){
checkboxes[i].checked = false;
}
}
if(_this.checked){
document.getElementById('result').innerHTML = document.getElementById(id).value;
}else{
document.getElementById('result').innerHTML = '';
}
}
input:-moz-read-only { /* For Firefox */
background-color: none;
border:none;
}
input:read-only {
background-color: none;
border:none;
}
<table id="userTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order Id</th>
<th>Order Proposed Id</th>
<th>Order Proposed Date</th>
<th>Store Id</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>1001</td>
<td>
<input type="text" value="123" readonly="true" id="opID_1"/>
</td>
<td>Order Proposed Date</td>
<td>Store Id</td>
<td>
<input type='checkbox' onchange="selectedValue('opID_1',this)" class="selectedIN"/>
</td>
</tr>
<tr>
<td>5555</td>
<td>
<input type="text" value="456" readonly="true" id="opID_2"/>
</td>
<td>Order Proposed Date</td>
<td>Store Id</td>
<td>
<input type='checkbox' onchange="selectedValue('opID_2',this)" class="selectedIN"/>
</td>
</tr>
<tr>
<td>5555</td>
<td>
<input type="text" value="789" readonly="true" id="opID_3"/>
</td>
<td>Order Proposed Date</td>
<td>Store Id</td>
<td>
<input type='checkbox' onchange="selectedValue('opID_3',this)" class="selectedIN"/>
</td>
</tr>
<tr>
<td>5555</td>
<td>
<input type="text" value="999" readonly="true" id="opID_4"/>
</td>
<td>Order Proposed Date</td>
<td>Store Id</td>
<td>
<input type='checkbox' onchange="selectedValue('opID_4',this)" class="selectedIN"/>
</td>
</tr>
</table>
<div class='selected_values'>
<strong>Selected Value: <span id="result"></span></strong>
</div>
</tbody>
var inputs = [].slice.call(document.querySelectorAll("#userTable input[type=checkbox]"));
function generateText() {
return inputs.reduce(function(builtList, input) {
if (input.checked) {
return builtList.concat(input.value);
}
return builtList;
}, []).join();
}
var textarea = document.querySelector("textarea");
inputs.forEach(function(input) {
input.addEventListener("click", function() {
textarea.value = generateText();
});
});
Preferably, you'd use a better way (such as document.getElementById()) to select the text area, but you didn't include it in your code so I don't know its ID
You can detect the checkbox checked or not with onchange function of Jquery. After that you just select the its Order Proposal Id using by parent and find functions.
I added Jquery 2.1.1 to the below snippet.
$("input").on("change",function(){
var thiz = $(this);
if(thiz.is(':checked')){
var value = thiz.parent().parent().find("td:nth-child(2)").text();
$(".selected_values span").text(value);
}
else{
$(".selected_values span").text("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border='1'>
<tr>
<th>Order Id</th>
<th>Order Proposal Id</th>
<th>Order Proposal Date</th>
<th>Store Id</th>
<th>Store Id</th>
</tr>
<tr>
<td>2</td>
<td>1001</td>
<td>2016-10-21</td>
<td>1709</td>
<td>
<input type='checkbox'/>
</td>
</tr>
<tr>
<td>10</td>
<td>82715421</td>
<td>2017-05-22</td>
<td>525</td>
<td>
<input type='checkbox'/>
</td>
</tr>
<tr>
<td>11</td>
<td>82715422</td>
<td>2016-12-31</td>
<td>525</td>
<td>
<input type='checkbox'/>
</td>
</tr>
</table>
<div class='selected_values'>
<strong>Selected Value: <span></span></strong>
</div>
Pure Javascript Solution
var value_span = document.getElementById("selected_value");
function printSelectedValue(e, selected_value){
if (e.checked) {
value_span.textContent = selected_value;
}
else{
value_span.textContent = "";
}
}
<table border='1'>
<tr>
<th>Order Id</th>
<th>Order Proposal Id</th>
<th>Order Proposal Date</th>
<th>Store Id</th>
<th>Store Id</th>
</tr>
<tr>
<td>2</td>
<td>1001</td>
<td>2016-10-21</td>
<td>1709</td>
<td>
<input type='checkbox' onChange="printSelectedValue(this,'1001')"/>
</td>
</tr>
<tr>
<td>10</td>
<td>82715421</td>
<td>2017-05-22</td>
<td>525</td>
<td>
<input type='checkbox' onChange="printSelectedValue(this,'82715421')"/>
</td>
</tr>
<tr>
<td>11</td>
<td>82715422</td>
<td>2016-12-31</td>
<td>525</td>
<td>
<input type='checkbox' onChange="printSelectedValue(this,'82715422')"/>
</td>
</tr>
</table>
<div>
<strong>Selected Value: <span id='selected_value'></span></strong>
</div>

How to multiply two value on focus of any text box using javascript?

I have a table in which I have some columns:
<table id="TableID1">
<thead>
<tr>
<th>Sr. No.</th>
<th>Item Code</th>
<th>Description</th>
<th>Quantity</th>
<th width="10%">Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>TE0011200MAH3VG00</td>
<td>3 d1,</td>
<td>12</td>
<td><input type="number"></td>
<td><input type="number"></td>
</tr>
<tr>
<td>6</td>
<td>SG0246100KAD1HG10</td>
<td>3 d1,</td>
<td>12</td>
<td><input type="number"></td>
<td><input type="number"></td>
</tr>
</tbody>
</table>
If a user adds some value in the "Price" column then I multiply "Quantity" and "Price" and show the result in the third column "Total" in the same row. It will have to run time. Please give me a solution in javascript or jQuery.
You can do it like this :
$("#TableID1").find("input").change(function(){
var getVal = $(this).parent().index();
var multiply = Number($(this).parent().parent().find("td").eq(getVal-1).text()) * $(this).val();
$(this).parent().parent().find("td").eq(getVal+1).find("input").val(multiply)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="TableID1">
<thead>
<tr>
<th>Sr. No.</th>
<th>Item Code</th>
<th>Description</th>
<th>Quantity</th>
<th width="10%">Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>TE0011200MAH3VG00</td>
<td>3 d1,</td>
<td>12</td>
<td>
<input type="number">
</td>
<td>
<input type="number">
</td>
</tr>
<tr>
<td>6</td>
<td>SG0246100KAD1HG10</td>
<td>3 d1,</td>
<td>12</td>
<td>
<input type="number">
</td>
<td>
<input type="number">
</td>
</tr>
</tbody>
</table>
Hope it helps :)
Attach input event handler and update the input based on the value.
$(document).ready(function() {
$('tr td:nth-child(5) input').on('input', function() {
// get input in last column and set value
$(this).closest('tr').find('td:nth-child(6) input').val(
// get value from input, and use `+` to convert string to number
+$(this).val() *
// get quantity value and multiply
+$(this).closest('tr').find('td:nth-child(4)').text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="TableID1">
<thead>
<tr>
<th>Sr. No.</th>
<th>Item Code</th>
<th>Description</th>
<th>Quantity</th>
<th width="10%">Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>TE0011200MAH3VG00</td>
<td>3 d1,</td>
<td>12</td>
<td>
<input type="number">
</td>
<td>
<input type="number">
</td>
</tr>
<tr>
<td>6</td>
<td>SG0246100KAD1HG10</td>
<td>3 d1,</td>
<td>12</td>
<td>
<input type="number">
</td>
<td>
<input type="number">
</td>
</tr>
</tbody>
</table>

Categories