How to delete a table row by id except specific id - javascript

I have atable where I want to delete all its rows except some rows with specific ids.
I did the follwoing:
for(var y=0; y<table.rows.length; y++)
{
console.log("deleting row "+ y);
var initialRow=document.getElementById("initial-row");
if (table.rows[y].id!=initialRow)
{
table.deleteRow(y);
console.log("row deleted");
}
else continue;
}
But this did not work. Any suggestions?
EDIT:
Here is the HTML table:
<table align='center' cellspacing=1 cellpadding=1 id="data-table" border=1>
<tr id="head">
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
<tr id="initial-row">
<td><input type="text" id="text-field"></td>
<td>
<select name="levels-list" id="levels-list">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" id="add-button" value="Add"></td>
</tr>
</table>
I am adding rows dynamically int the javascript. Then, I need to delete a row, and refresh the whole table as the added rows ids are dynamic. In order to refresh the table, I want to delete all the old rows except the header and the initial row that was in the HTML page originally. Could not do this correctly.

You're comparing an element id (a string) to a DOM element object. You can remove the getElementById call and simply do:
if (table.rows[y].id!="initial-row")

Related

Read cell Contents Dynamic JS/Jquery table

I am using JS/Jquery to dynamically add rows to by Table. Here is a template that I found online:
<table id="tblCustomers" cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtCountry" /></td>
<td><input type="button" onclick="Add()" value="Add" /></td>
</tr>
</tfoot>
</table>
From what I gather, in order to ensure that the actual cell content values get passed on Post I need to assign them to hidden fields.
How do I read the actual contents of the cells.
I tried:
$("#submitForm").click(function(){
alert("submit Clicked");
$('#tblCustomers tfoot td').each(function() {
var cellText = $(this).html();
});
});
however, All I got was this as return value:
Can you let me know what I need to do to get actual value of cell.
I need to make a dynamic table/item list and i would like to send the list of items back to server for processing. Sort of like a purchase list etc..
BTW: the backend is Django 2.0
Thanks for your help.
Tanmay

Using html select to make ajax refresh to filter table

As mentioned in the title, I want to know how to make an HTML select box to make an ajax request and use that to filter table. I have searched a lot and was not able to find a good solution.
How can i get it to filter??
My source code on jsfiddle.net:
<select>
<option value="all">All</option>
<option value="tim">Tim</option>
<option value="cook">Cook</option>
</select>
<br>
<br>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>Year</th>
</tr>
<tr>
<td>Tim</td>
<td>2015</td>
</tr>
<tr>
<td>Cook</td>
<td>2015</td>
</tr>
</table>
Your example is a little odd because you are filtering down to only one row, but here is how you can make it work.
First, give your <select> and <table> each an id. I chose something generic:
<select id='column-select'>
<option value="all">All</option>
<option value="tim">Tim</option>
<option value="cook">Cook</option>
</select>
<br>
<br>
<br>
<table id='data' border="1">
<tr>
<th>Name</th>
<th>Year</th>
</tr>
<tr>
<td>Tim</td>
<td>2015</td>
</tr>
<tr>
<td>Cook</td>
<td>2015</td>
</tr>
</table>
Now, just use some Jquery to filter out the rows you don't want when the column changes
$(document).ready(function() { // Do nothing until document is ready
$("#column-select").change(function() { // On <select> change...
var selection = $("#column-select").val();
if (selection == "all")
{
$("#data tr").show(); // Show all rows
} else
{
$("#data tr").each(function() { // For each row
if ($(this).find("th").length == 0) // If this is not a heading row
{
if ($(this).find("td").eq(0).text().toLowerCase() == selection)
{
// Show rows where the first column matches
$(this).show();
} else
}
// Hide rows where the first column does not match
$(this).hide();
}
}
});
}
});
});
Here is a jsfiddle to demonstrate.

Jquery clone event handling not working

I am trying to retrieve the index of the row when the user has clicked on the check box. It works for the codes that I have written for the first two rows when the check box are ticked. However when I tried to insert more rows, the index that I retrieve after the check box is tick gave me a false result, i.e -1.
Can anyone help me with this? I have research for a long time and I still can't get it to work. I tried setting the clone argument to true but it still failed.
//Insert a new row after the last row in the table
$("#add").click(function() {
clickCount++;
var numRows = $('#getnumRows').val();
var index = $('#mytable tbody>tr:last td:nth-child(2)').text();
var i=Number(index);
var intNumRow=Number(numRows)+i;
for (; i < intNumRow; i++)
{
$('#mytable tbody>tr:last').clone(true,true).insertAfter('#mytable tbody>tr:last');
//$("#mytable tbody>tr>td:last td:nth-child(1)").children('input').addClass('chkbox');
$('#mytable tbody>tr:last td:nth-child(2)').text(i+1);
var input= $('#mytable tbody>tr:last').find('td').children('input');
input.val('');
input.attr("checked", false);
}
});//end click tag
var chkBox=$("#mytable tbody>tr>td ").children('.chkbox');
chkBox.on('click',null,function ()
{
var isChecked=$('.chkbox');
if (isChecked.is(':checked')) {
var index=chkBox.index(this);
alert(index); //added alert to intentional check the index retrieve from the checked checkbox of the row![enter image description here][1]
var insertNewRow=ajaxNewRowInfo(partNo,serviceName);
insertNewRow.success(function(data)
{
var row=$('#mytable tbody>tr').eq(index);
for(i=2;i<data.length;i++)
{
$(row.children(' td:nth-child('+(i+3)+')')).children('input').val(data[i]);
}
});//insertNewRow end tag
}//if end tag
else{
alert('You Un-Checked it');
}
});//chckbox end tag
<!--Add rows -->
<div class="form-group">
<label class="col-sm-1 control-label" style='margin-top:0.6%;'>Rows</label>
<input class="form-control" style='width:100px;' type='text' id='getnumRows' placeholder='No.of Rows'>
<button type="submit" id="add" class="btn btn-success" style="margin-left:200px; margin-top:-35px; ">Add rows</button>
</div>
<!------------->
<tbody>
<tr id='tableRow1'>
<td><input type="checkbox" class='chkbox'/></td>
<td> 1</td>
<td>
<select class="form-control" class="serviceDropdown">
<option></option>
<option value='1'>Oil Change Service</option>
<option value='2'> Tyre Service</option>
<option value='3'>Vehicle Service</option>
<option value='4'>Battery Service</option>
<option value='5'>Clutch Brake Service</option>
<option value='6'>Suspension Service</option>
<option value='7'>Brake Service</option>
<option value='8'>Tuning and Diagnostic Service</option>
</select>
</td>
</tbody>
[The first image shows the alert box which the index of the check box row is able to retrieved. The second image shows when new rows are added through cloning, the index of the alert box shows -1.]
http://postimg.org/image/913o3lyuv/
http://postimg.org/image/fg2p0a5kn/
Consider Element Indexing w/ jQuery Index()
Ex. http://codepen.io/anon/pen/XJRJEg
If .index() is called on a collection of elements and a DOM element or
jQuery object is passed in, .index() returns an integer indicating the
position of the passed element relative to the original collection.
HTML
<table id="hi">
<thead>
<tr>
<th>Heading</th>
<th>Heading 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
jQuery
$( "table#hi tbody tr" ).click(function() {
var index = $( "table#hi tbody tr" ).index( this );
alert(index);
});
DOCUMENTATION

How to get the count of checked rows of a table on a button click using jQuery?

I'm working with Asp .net MVC3 following is my table,
<table id="myIndiaTable">
<thead>
<tr>
<th>Select All<input type="checkbox" class="chkhead" onchange="Getchecked()"/></th>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="chkdata"/></td>
<td>1</td>
<td>xxx</td>
</tr>
<tr>
<td><input type="checkbox" class="chkdata"/></td>
<td>2</td>
<td>yyytd>
</tr>
<tr>
<td><input type="checkbox" class="chkdata"/></td>
<td>3</td>
<td>zzz</td>
</tr>
</tbody>
</table>
<div class="btn">
<input type="button" name = "Submit" value ="Submit" onclick ="GetValues()"/>
</div>
When I click the submit button I have to get the count of selected rows count as an alert. How can I get this using jQuery?
USe :checked for getting the checked checkboxes,
$( ".chkdata:checked" ).length;
pure javascript
thi line ckbox = document.getElementsByClassName("chkdata"); will get all the element with class name chkdata return an array of element and then we loop through those element to check how many element are checked .if it is checked then we increment the counter otherwise continue to loop
ckbox = document.getElementsByClassName("chkdata");
count=0;
for(var i=0;i<ckbox.length;i++){
element = ckbox[i];
if(element.checked){
count++;
}
}
alert("Number : " + count);
You can get all the checked checkboxes with class chkdata inside the table myIndiaTable
function GetValues(){
alert($('#myIndiaTable .chkdata:checked').length)
}
to get only the checked checkboxs in the table use
$('#myIndiaTable').find("input[type='checkbox']:checked").length

Dynamically Add and Remove Table Rows

I am both adding and removing table rows with jQuery. I can add rows easily, but am having trouble removing ones that were created.
You can view the page in action here: http://freshbaby.com/v20/wic/request_quote.cfm, with the relevant code pasted below.
HTML
<table style="width:600px;" id="product-list" summary="Lists details about products users wish to purchase">
<thead valign="top" align="left">
<tr>
<th>Products</th>
<th>Language</th>
<th>Quantity</th>
<th></th>
</tr>
</thead>
<tbody valign="top" align="left">
<tr>
<td>
<cfselect query="getProductListing" name="product" size="1" display="name" value="name" queryPosition="below">
<option value=""></option>
</cfselect>
</td>
<td>
<select name="language" size="1">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
</td>
<td>
<cfinput name="quantity" required="yes" message="Enter your desired quantity" size="10" maxlength="3" mask="999">
</td>
<td valign="bottom">Add Another Product</td>
</tr>
</tbody>
</table>
JavaScript:
<script>
$(function() {
var i = 1;
$(".addrow").click(function() {
$("table#product-list tbody > tr:first").clone().find("input").each(function() {
$(this).attr({
'id': function(_, id) { return id + i },
'value': ''
});
}).end().find("a.addrow").removeClass('addrow').addClass('removerow').text('< Remove This Product')
.end().appendTo("table#product-list tbody");
i++;
return false;
});
$("a.removerow").click(function() {
//This should traverse up to the parent TR
$(this).parent().parent().remove();
return false;
});
});
</script>
When I click the link to remove the row that said link is contained in, nothing happens. No script error, so it has to be logic.
Try this instead
$("#product-list").on('click','a.removerow',function(e) {
e.preventDefault();
//This should traverse up to the parent TR
$(this).closest('tr').remove();
return false;
});
This will ensure that newly created elements can be removed. When you use the $("a.removerow").click(.. it only affects the elements in existence (none) and not the ones that will be dynamically created.

Categories