Code isn’t executed after removing rows in a table - javascript

I wrote a JavaScript function to remove selected rows in a table and it works fine but when I try to write some jQuery to change color of some button it doesn’t work. I have no clue what am I doing wrong.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button type="button" onclick="DeleteRow()" class="btn"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
<script>
function DeleteRow() { //this function delete selected rows from table
var i, chkbx, td;
var table = document.getElementById("myTable"); //table itself
var rows = table.getElementsByTagName("tr"); //rows in table-body
var numRows = rows.length; //number of rows
for (i = 1; i < numRows; i++) { //in this "for loop" , I try to remove selected rows
td = rows[i].getElementsByTagName("td")[0];
chkbx = td.getElementsByTagName("input")[0];
if (chkbx.checked == true) {
table.deleteRow(i);
--i; //each time we delete one row we decrease i
}
}
$(document).ready(function() {
$(".btn").css("background-color", "#ff0000");
}); //this jquery wont work
}
</script>
</body>
</html>

There are couple of issues in your loop causing an error, so I've fixed those, and moved your inline event listener to the JS file. Comments in the code. I also switched from jQuery to vanilla JS because there's no reason to use it if you're using vanilla JS everywhere else.
// Grab the button and add an click event for DeleteRow
document.querySelector(".btn").addEventListener('click', DeleteRow, false)
function DeleteRow() {
var i, chkbx, td;
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
// When removing items from the DOM it's usually a good idea
// to reverse the loop and simply use the length of the array.
// That way you don't have to decrement the index manually
for (let i = rows.length - 1; i > 0; i--) {
td = rows[i].getElementsByTagName("td")[0];
chkbx = td.getElementsByTagName("input")[0];
if (chkbx.checked == true) {
table.deleteRow(i);
}
}
// You don't have to use jQuery (it's a waste if everything
// else is native JS. Here we use `this` which is the element attached
// the click event
this.style.backgroundColor = '#ff0000';
}
<button type="button" class="btn"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td>
<input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>

A short refined version of your code could be like below. This will only change button background if the row is selected / deleted.
function DeleteRow() { //this function delete selected rows from table
var i, chkbx, td;
var table = $("#myTable tbody>tr input:checked"); //table itself
table.each(function() {
$(this).parent().parent().remove();
})
if (table.length) {
return true;
}
}
$(document).ready(function() {
$('#del').click(function() {
if (DeleteRow()) {
$(".btn").css("background-color", "#ff0000");
}
}); //this jquery wont work
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn" id="del"> delete </button>
<table id="myTable">
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>

If you already have jQuery, why are you mixing it with plain js? You can do this in jQuery very simply:
function DeleteRow() { //this function delete selected rows from table
$('input[type=checkbox]').each(function () {
if ($(this).prop('checked')) {
$(this).closest('tr').remove();
}
});
$(".btn").css("background-color", "#ff0000");
}

Related

"column select-all" using checkbox without affecting other column in a table php

I wanted to create a simple html select-all checkbox for my table form. So when we click on top of corresponding column list all the elements in the column are selected without checking other columns.
Here is what i tried..
<form name="checkn" id="frm1" class="form1" method="post">
<table class="table" cellspacing="10" border="1" style="width:100%;">
<thead>
<tr>
<th>Products List</th>
<th>
Product Available
<input type='checkbox' name='checkall' onclick='checkAll(frm1);'>
</th>
<th>
Description
<input type='checkbox' name='checkall' onclick='checkdAll(frm2);'>
</th>
</tr>
</thead>
<tbody>
<?php
//fetch data php code
?>
<tr> <td width="20%;"> <h3> <?=$products?> </h3> </td>
<td width="20%;"> <input id="frm1" type="checkbox" name="product1" value='<?=$fieldname?>' > Product Available </td>
<td width="20%;"> <input id="frm2" type="checkbox" name="product2"> Description </td>
</tr>
<button type="submit" name="submit" style="position:absolute; bottom:0;"> Submit </button>
<script type="text/javascript">
checked = false;
function checkAll (frm1)
{
var aa= document.getElementById('frm1'); if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
<script type="text/javascript">
checked = false;
function checkdAll (frm2)
{
var aa= document.getElementById('frm2'); if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
</tbody>
</table>
</form>
Please help me
I think you need to find all tr length then find td with input. after that, you can check all. Like this here is my code. I hope it helps you.
$('#IsSelectAll').on('change', function () {
if ($(this).is(':checked')) {
$('#tbCustomerList tbody tr:visible').filter(function () {
$(this).find('td:eq(1)').children('label').children('input[type=checkbox]').prop('checked', true);
});
}
else {
$('#tbCustomerList tbody tr:visible').filter(function () {
$(this).find('td:eq(1)').children('label').children('input[type=checkbox]').prop('checked', false);
});
}
});

Counting rows on a particular table

I have a page that the user can dynamically add rows or tables to. I need to count the rows on a given table using jQuery to see if I just need to insert a row or a row and the header. Right now the count is just counting all rows on all tables. I am using jQuery 1.7.2 and the jquery templeter.
<div id="ClonePoint">
<button id="exitSection" class="closesection"><span>Close</span></button> <br /> <br />
<button class="btnEncode" id="buttonEncode">Encode</button>
<input id="encryptedTokenClone" />
<button class="btnDecode" id="buttonDecode">Decode</button>
<table class="tokenTable" cellpadding="3px">
<tbody class="tokenBody" >
</tbody>
</table>
<button id="addRow" class="addingRow">Add Row</button>
</div>
And the jQuery that is adding the rows
$('#BackgroundArea').on('click', '.addingRow', function () {
var selectedDiv = $(this).parent();
var selectedTable = $(selectedDiv).children('.tokenTable');
var rowCount = 0;
rowCount = $('.tokenTable .tokenBody').children('tr').length;
if (rowCount > 0) {
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
} else {
$("#TableHeader")
.tmpl()
.appendTo(selectedTable);
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
}
});
The html for the insert is
<script id="TableHeader" type="text/html">
<tr id="TableHead">
<th width="55px">Delete Row</th>
<th align="right"> Key </th>
<th align="left"> Value </th>
</tr>
</script>
<script id="tokenAddRowTemplate" type="text/html">
<tr id="tokenRow">
<td class="deleteRow" id="tokenCell">
<button class="deleteRow">
<span>delete row</span>
</button>
</td>
<td class="keyValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
<td class="valueValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
</tr>
</script>
This should give tr count in your table.
$("#yourTableId tr").length
Is this what your are looking for ?
If each table is followed by its own "Add Row" button:
var $table = $(this).prev(),
rowCount = $table.find('.tokenBody').children('tr').length;
if (rowCount > 0) {
...
This assumes the "Add Row" button immediately follows the table.
To make the code less brittle, you could consider using a container element, like this:
<div class="tokenTableContainer">
<table class="tokenTable">
...
<table>
<button class="addingRow">...</button>
</div>
Then you can do this:
$('.addingRow').click(function() {
var $table = $(this).closest('.tokenTableContainer').find('.tokenTable');
...
});

Deleting a specific row in a table

I'm trying to delete a specific row from a table using javascript. The way I'm trying to do it now, is by retrieving the ID of the current row by clicking a button (the delete button) and then deleting the row. The problem is that I'm not retrieving the current row ID in the table. If someone could help me retrieve the the ID of the current row when the user clicks the delete button, I think I can solve the rest myself. Thanks
/*The Javascript*/
function delete_row() {
alert('id goes here');
//getElementById('row').innerHTML ='hello';
//id.deleteRow();
//var table = document.getElementByTagName('items_table');
//var row = table.rows[index];
//document.getElementByTagName('items_table').deleteRow(0);
}
/*The HTML of the Table*/
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
/* Five rows in this table... */
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row();">X</button>
</td>
</tr>
</table>
You could just ascend the tree until you find a row:
function delete_row(btn) {
var tr = btn;
while(tr && tr.nodeName != "TR") tr = tr.parentNode;
if( !tr) throw new Error("Failed to find the row, was the function called correctly?");
tr.parentNode.removeChild(tr); // delete it
}
And:
<button onClick="delete_row(this);">X</button>
The this is important, as it provides a reference to the button that was clicked, so we can find the row it is in.
Check this code. It has been verified and will do your job perfectly. :)
<script>
function delete_row(me) {
alert(me.parentNode.parentNode.id);
}
</script>
<table id="items_table">
<tr id="row_1">
<td>
<input type="text" value="item1"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
<tr id="row_5">
<td>
<input type="text" value="item5"/>
</td>
<td>
<button onclick="delete_row(this);">X</button>
</td>
</tr>
</table>
Can't you just change <button onclick="delete_row();">X</button> to <button onclick="delete_row('row_5');">X</button>, in each row, respectively?
Your handler would look like:
function delete_row(theID) {
alert(theID);
}

Dynamically changing the Tab Index for the textbox

I have a requirement to accomplish to change the tab index of the cursor based on how the user wishes to perform. I am not sure what is the best way to achieve this. I have created a fiddle to ensure what is explained here is understood by all.
The requirement is the following:
There is a table with a series of text box on all the rows and columns.
A radio button is provided below the table for the user to be able to move through the text boxes on the table.
Selecting "Move Horizontally" will make the cursor move from each textbox horizontally when a tab is pressed or the max length is reached.
Selection "Move Vertically" will make the cursor move from each textbox vertically when a tab is pressed or the max length is reached.
By default the tab indexes move vertically.
When reaching the last textbox on either the row on the column, the cursor should automatically move to the next row or columns first textbox.
How can I achieve this dynamically when selecting the radio buttons.
JS Fiddle: http://jsfiddle.net/2uzfT/4/embedded/result/
Your Complete Solution :)
HTML
<table border="1" id="mytable">
<thead>
<tr>
<th> Description </th>
<th> Column1 </th>
<th> Column2 </th>
<th> Column3 </th>
</tr>
</thead>
<tbody>
<tr>
<td> Stephen </td>
<td><input type="text">
</td>
<td><input type="text">
</td>
<td><input type="text">
</td>
</tr>
<tr>
<td> Malcom </td>
<td><input type="text">
</td>
<td><input type="text">
</td>
<td><input type="text">
</td>
</tr>
<tr>
<td> Judith </td>
<td><input type="text">
</td>
<td><input type="text">
</td>
<td><input type="text">
</td>
</tr>
</tbody>
</table>
<br>
<br>
<INPUT TYPE=RADIO NAME="selection" VALUE="V">
Move Verically<BR>
<INPUT TYPE=RADIO NAME="selection" VALUE="H">
Move Horizontally<BR>
jQuery
$(function() {
var inputBox = $('#mytable input[type="text"]').length;
var row = $('#mytable tbody tr').length;
var column = $('#mytable tbody tr:first td').length;
// Vertical
$('input:radio').change(function() {
var self = $(this);
if(self.val() == "V") {
var counter = 1;
for(i=1; i<column; i++) {
for(j=2; j<=row+1; j++) {
$('#mytable tbody tr td:nth-child('+j+')').find('input[type="text"]').attr('tabindex', counter);
counter++;
}
}
}
else {
$('#mytable input[type="text"]').removeAttr('tabindex');
}
});
});
A rough idea is below by jQuery:
// For columns
var textBoxes = $('#tableid input[type="textbox"]').length;
var rowNums = 4;
for(i=0; i<=textBoxes; i++) {
for(j=0; j<=rowNums; j++) {
$('#tableid').find('tr:eq('+j+') input[type="textbox"]').attr('tabindex', i);
}
}
Row indexing can be done also same as above

click anywhere on a table row and it will check the checkbox its in...?

I'm trying to figure out how to do this, but I can't find it out. Basically I want to be able to click anywhere on a table row and it will check/ unchecked the checkbox its in. I know it's possible because that's what PHPMyAdmin does...
here is my table row
<tbody>
<tr id="1" onclick="selectRow(1)"><td width="20px"><input type="checkbox" id="1" name="1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr id="2" onclick="selectRow(2)"><td width="20px"><input type="checkbox" id="2" name="2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
<script type="text/javascript">
function selectRow(row)
{
var firstInput = row.getElementsByTagName('input')[0];
firstInput.checked = !firstInput.checked;
}
</script>
...
<tbody>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk1" name="chk1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
<tr onclick="selectRow(this)"><td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>
</tbody>
Note: You've also got collisions on ids. Your ids should be unique.
Here's an alternative with programmatic binding:
document.querySelector("table").addEventListener("click", ({target}) => {
// discard direct clicks on input elements
if (target.nodeName === "INPUT") return;
// get the nearest tr
const tr = target.closest("tr");
if (tr) {
// if it exists, get the first checkbox
const checkbox = tr.querySelector("input[type='checkbox']");
if (checkbox) {
// if it exists, toggle the checked property
checkbox.checked = !checkbox.checked;
}
}
});
<table>
<tbody>
<tr>
<td>
<input type="checkbox" id="chk1" name="chk1" />
</td>
<td>1</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk2" />
</td>
<td>2</td>
<td>2011-04-21 22:04:56</td>
<td>action</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chk2" name="chk3" />
</td>
<td>2</td>
<td>2011-04-21 25:30:16</td>
<td>action</td>
</tr>
</tbody>
</table>
You don't need JavaScript for this:
td label {
display: block;
}
<td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td><label for="chk2">2</label></td><td><label for="chk2">2011-04-21 22:04:56</label></td><td><label for="chk2">action</label></td>
Just labels and a little CSS.
Try this one out...
$("tr").click(function() {
var checkbox = $(this).find("input[type='checkbox']");
checkbox.attr('checked', !checkbox.attr('checked'));
});
http://jsfiddle.net/dVay8/
Since this question getting so many views and the accepted answer has a small issue.
The issue is when you click on the checkbox it won't change. Actually what happens is the checkbox toggles twice. Because of we clicked on the checkbox and the table row as well. So here is a proper solution with a fix.
$('tr').click(function(event){
var $target = $(event.target);
if(!$target.is('input:checkbox'))
{
$(this).find('input:checkbox').each(function() {
if(this.checked) this.checked = false;
else this.checked = true;
})
}
});
Good luck devs.

Categories

Resources