I have a MVC web app in which I show a table.
Some of my rows can have a similar id, on which I need to show only one checkbox for all those rows, and individual checkboxes for the rows which don't have a matching id. Something like below:
row1 and row2 have the same id, hence the checkbox is in between them (denoted by red checkbox).
row3, row4 have different ids, hence they need to have their individual checkboxes (denoted by green).
I know I need to play on the rowspan property, but I am unable to visualize how to get on it.
Below is the sample code:
[Route("Search")]
[HttpGet]
public async Task<IActionResult> Search()
{
//Some API call
return View("Search", model);
}
View Code:
<table id="tblsearch">
#if (Model.HasRecords)
{
var counter = 0;
<tbody>
#foreach (var item in Model.SearchResults)
{
<tr>
<td>
<input type="checkbox" id="Dummy_#counter" name="chkSearch" data-id="#item.Id"/>
<label for="Dummy_#counter"></label>
</td>
<td>#item.FullAddress</td>
<td>#item.Price</td>
<td>#item.OfficeName</td>
}
else
{
<tr><td>Data Not Found</td></tr>
}
</table>
I am trying to first hide all the checkboxes, then trying to match the id's in each row, and then if the ids of 2 rows are same, I am trying to increase the rowspan by 2.
js code:
function pageLoad()
{
var rowCount = $('#tblSearch >tbody >tr').length;
for(var i=0;i<rowCount-1;i++)
{
$('#Dummy_' + i).hide();
}
var searchArray= [];
for (var i = 0; i < rowCount - 1; i++) {
searchArray[i]= $('#tblSearch >tbody >tr')[i].attr('data-id');
}
}
Please guide how to proceed.
You should control the layout of the page in this instance from your View, please forgive my syntax as I primarily work in vbhtml these days.
Important things are to order your search results (in case they aren't already)
Remember and update the last processed Id.
<table id="tblsearch">
#if (Model.HasRecords)
{
var counter = 0;
var lastId = -1;
<tbody>
#foreach (var item in Model.SearchResults.OrderBy(x=>x.Id))
{
<tr>
#if(lastId!= item.Id){
<td rowspan="#(Model.SearchResults.Count(x=>x.Id == item.Id) > 0 ? Model.SearchResults.Count(x=>x.Id == item.Id) : 1 )">
<input type="checkbox" id="Dummy_#counter" name="chkSearch" data-id="#item.Id"/>
<label for="Dummy_#counter"></label>
</td>
}
<td>#item.FullAddress</td>
<td>#item.Price</td>
<td>#item.OfficeName</td>
#lastId = item.Id;
//I assume there was code snipped here...
}
else
{
<tr><td>Data Not Found</td></tr>
}
</table>
There is no need for any javascript. You can simply group your items by the Id property and conditionally render the checkbox column with a rowspan attribute if its the first item in the group.
<tbody>
#foreach (var group in Model.SearchResults.GroupBy(x => x.Id))
{
bool isFirstRow = true;
foreach (var item in group)
{
<tr>
#if (isFirstRow)
{
<td rowspan="#group.Count()">
#Html.CheckBox("chkSearch")
</td>
isFirstRow = false;
}
<td>#item.FullAddress</td>
<td>#item.Price</td>
<td>#item.OfficeName</td>
</tr>
}
}
</tbody>
Related
In my form I have a table with checkbox in all of these columns. I have 3 <tr> and each <tr> has its ng-repeate calling the webservice to display the clones (Json data).
When I click on a checkbox I generate a js array which records id using this code :
checkoptions (array, model) {
angular.forEach(array, (value, key) => {
if (array[key].checked) {
model.push(array[key].id)
}
})
And in HTML :
<tr ng-repeat="developer in $ctrl.developers">
<td>{{developer.label}}</td>
<td>
<input type="checkbox" id="{{developer.id}}"
ng-change="$ctrl.checkoptions($ctrl.developers,$ctrl.employees.developers)"
ng-model="developer.checked">
<label for="{{developer.id}}"></label>
</td>
It works, but the problem is that when I uncheck a checkbox it is not removed from the js array
I included an else part to remove from the array:
http://jsfiddle.net/x9m1nqvp/1/
$scope.checkoptions = function (array, model) {
angular.forEach(array, (value, key) => {
if (array[key].checked) {
var index = model.indexOf(array[key].id);
if(index == -1)
model.push(array[key].id)
}
else {
var index = model.indexOf(array[key].id);
if(index >=0)
model.splice(index, 1);
}
})
While Everton's answer gets the job done, it is a bit redundant checking every item in the array, every time a single checkbox changes state. You don't really have to update for every single item in the array.
Here is an example, where only the checkbox that's actually toggled, is added or removed from the employees.developers array (Note: no need for the redundant angular.forEach):
$scope.checkoption = function (developer){
if (developer.checked) {
var index = $scope.employees.developers.indexOf(developer.id);
if(index == -1)
$scope.employees.developers.push(developer.id)
} else {
var index = $scope.employees.developers.indexOf(developer.id);
if(index >=0)
$scope.employees.developers.splice(index, 1);
}
}
and how this is used in the html:
<tr ng-repeat="developer in developers">
<td>{{developer.label}}</td>
<td>
<input type="checkbox" id="{{developer.id}}"
ng-change="checkoption(developer)"
ng-model="developer.checked">
<label for="{{developer.id}}"></label>
</td>
</tr>
Am working on the table, my aim is to display rows orderly based on its sum of columns. I mean, highest valued rows should be displayed first and then, second highest values, then, go on.. Have tried and could not make it. Just give me an idea, and that is good enough for me. Am not able to come to any idea on how to reshuffle the rows based on its sum values. Any idea on this?
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<form>
<input type="radio" value="All" onclick="Turnthis();"/>All
<input type="radio" value="Top15" onclick="TurnOutthis();"/>Top5
</form>
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
</table>
</div>
After I pressed the 'Top5' button, then, the table should be displayed as follows[sample]
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<form>
<input type="radio" value="All" onclick="Turnthis();"/>All
<input type="radio" value="Top15" onclick="TurnOutthis();"/>Top5
</form>
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
</tbody>
</table></div>
Hope this makes sense. For your kind information, i except code only in javascript not in jquery.
The trick is to get the rows you want and put them into an array, then sort the array and put the rows into the table in the right order. The following will sort the rows based on the cell values, so if the first cell value is equal, it uses the second, and so on. The sort may not be stable since it just uses the built–in Array.prototype.sort. If you want to to be stable, that is pretty simple (but generally not required).
Firstly, get the relevant tBody element and rows:
var tBody = document.getElementById('bt_01').tBodies[0];
var rows = tBody.rows;
rows is a live collection so you want to build an array form it (also helps with sorting). The following works fine in modern browsers:
var rowArr = Array.prototype.slice.call(rows);
But will not work in IE 8 and lower, you'll need to use a for loop (just one extra line of code):
var rowArr = [];
for (var i=0, iLen=rows.length; i<iLen; i++) rowArr[i] = rows[i];
To keep the last row as the last, just keep a reference:
var lastRow = rowArr[rowArr.length - 1];
Now sort based on the cell values from the second cell onward:
rowArr.sort(function(a, b) {
var aVal, bVal;
for (var i = 1, iLen = a.cells.length; i<iLen; i++) {
aVal = a.cells[i].textContent || a.cells[i].innerText;
bVal = b.cells[i].textContent || b.cells[i].innerText;
if (aVal != bVal) return aVal - bVal;
}
return 0;
});
Now put the rows into order:
for (var j=0, jLen=rowArr.length; j<jLen; j++) {
tBody.appendChild(rowArr[j]);
}
and finally, put the bottom row back at the bottom:
tBody.appendChild(lastRow);
and you're done. And it's shorter than the offered jQuery alternative (and likely a lot faster). ;-)
It would be best to put footer row in separate tFoot section as you've done with the header.
Edit
If you want to sort based on the sum of the values in each row, the sort part becomes:
rowArr.sort(function(a, b) {
var aSum = 0, bSum = 0;
for (var i = 1, iLen = a.cells.length; i<iLen; i++) {
aSum += parseFloat(a.cells[i].textContent || a.cells[i].innerText);
bSum += parseFloat(b.cells[i].textContent || b.cells[i].innerText);
}
return aSum - bSum;
});
I assume you want the "total" row at the end of the table after sort.Otherwise code can be 10-12 lines shorter.
i come up with this solution.I've commented out every portion for convenience .With a little help form getElementsByTagName,removeChild,createElement,and appendChild methods you can achieve what you are trying to do.It is really simple.I advice you go through it.The main thing is create an array of objects which hold three properties.And the properties are the actual tr element,its sum and the first td element which holds subject1,2,3....and Total string.Then sort them down with Array.prototype.sort() then add them serially to your tbody element
var radio=document.getElementById('radio');
if(radio.checked == true){ //check for radio element is checked or not
radio.checked=false;
}
var table=document.getElementById('bt_01');
var serialTdArr=[]; //array which will hold the array of objects
var storageForTotal='';// store the tr element that has 'Total' as value of its first td element
function Turnthis(e){
var tbody=document.getElementsByTagName('tbody')[0]; //get the current tbody element
var tr=tbody.getElementsByTagName('tr'); //get all tr elements inside tbody
for(i=0;i<tr.length;i++){ // loop over the tr elements
var sum=0;
var td=tr[i].getElementsByTagName('td'); //get all td element inside every tr element
for(j=1;j<td.length;j++){
sum+=parseInt(td[j].innerHTML); // sum them up
}
var firstTd=td[0].innerHTML; //save every subject1,subject2,3,...and Total string to a seperate variable
serialTdArr.push({index:tr[i],sum:sum,pointer:firstTd}); // an object which holds the tr element,its sum and its first td element value is pushed inside serialTdArr
}
var sortedArr=serialTdArr.sort(function(a,b){ // sort them down from higher to lower
if(a.sum < b.sum){
return 1;
}
if(a.sum > b.sum){
return -1;
}
return 0;
});
table.removeChild(tbody); // remove the current tbody
var newTbody=document.createElement('tbody'); // create a new tbody
table.appendChild(newTbody); // append it to table
for(i=0;i<sortedArr.length;i++){
if((sortedArr[i].pointer) != 'Total'){ // if it has no "Total" string then add them to tbody
newTbody.appendChild(sortedArr[i].index); // add to tbody
}else{
storageForTotal=sortedArr[i].index; // 'Total' row will be seperated and stored in a variable to be added later at the end of the table
}
}
newTbody.appendChild(storageForTotal); // add the tr which 'Total' to the last of td element
}
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<form>
<input type="radio" id='radio' value="Sort Them All" onchange="Turnthis();"/>Sort Them All
</form>
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
This code works and tested on Chrome 30
Non-jQuery version (updated question):
<html>
<body>
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
<tfoot>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tfoot>
</table>
</div>
<input type='button' onclick='sort()' value='sort by sum' />
<script>
function sort() {
var t = document.getElementById('bt_01').children[1]; // tbody
var arr = [];
// find all tr
var trs = t.children;
for(;trs.length;) {
var tr = trs[0];
// find all td and calculate the sum
var sum = 0;
var tds = tr.children;
for(var y in tds) {
var td = tds[y];
var v = +td.textContent;
if (!isNaN(v)) sum += v;
};
// move them to arr
tr = tr.parentNode.removeChild(tr)
arr.push({sum: sum,tr: tr});
};
// sort it
arr.sort(function(a, b) {
if (a.sum < b.sum) return 1;
if (a.sum > b.sum) return -1;
return 0;
});
// attach back the tr in order
for (var z in arr) t.appendChild(arr[z].tr)
}
</script>
</body>
</html>
jQuery version:
<html>
<body>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<div id="na_1" style="border: 1px solid gray;width: 450px;padding:10px;">
<table id="bt_01" border="1" width="100%">
<thead>
<tr><td>head1</td><td>head2</td><td>head3</td><td>head4</td><td>head5</td><td>head6</td><td>head7</td></tr>
</thead>
<tbody>
<tr><td>Subject1</td><td>501</td><td>501</td><td>501</td><td>550</td><td>560</td><td>570</td></tr>
<tr><td>Subject2</td><td>620</td><td>640</td><td>605</td><td>650</td><td>600</td><td>604</td></tr>
<tr><td>Subject3</td><td>730</td><td>730</td><td>740</td><td>750</td><td>760</td><td>790</td></tr>
<tr><td>Subject4</td><td>700</td><td>701</td><td>700</td><td>702</td><td>700</td><td>703</td></tr>
<tr><td>Subject5</td><td>220</td><td>201</td><td>202</td><td>222</td><td>210</td><td>203</td></tr>
<tr><td>Subject6</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject7</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
<tr><td>Subject8</td><td>200</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tbody>
<tfoot>
<tr><td>Total</td><td>202</td><td>201</td><td>200</td><td>202</td><td>200</td><td>203</td></tr>
</tfoot>
</table>
</div>
<input type='button' onclick='sort()' value='sort by sum' />
<script>
function sort() {
var t = $('#bt_01').find('tbody');
var arr = [];
// find all tr
t.find('tr').each(function(idx, tr) {
tr = $(tr);
// find all td and calculate the sum
var sum = 0;
tr.find('td').each(function(idx, td) {
td = $(td);
var v = +td.text();
if (!isNaN(v)) sum += v;
});
// move them to arr
arr.push({sum: sum,tr: tr.detach()});
});
// sort it
arr.sort(function(a, b) {
if (a.sum < b.sum) return 1;
if (a.sum > b.sum) return -1;
return 0;
});
// attach back the tr in order
for (var z in arr) t.append(arr[z].tr)
}
</script>
</body>
</html>
I've got a table-like structure with text inputs in which I am trying to make an entire row to be removed with all their children, but first passing the values of cells up one by one
in the rows below to keep IDs numbering structure.
The table structure is like this:
<table cellpadding=0>
<tr id="myRow1">
<td id="#R1C1">
<input class="myCell">
</td>
<td id="#R1C2">
<input class="myCell">
</td>
<td id="#R1C3">
<input class="myCell">
</td>
<td id="#R1C4">
<input class="myCell">
</td>
</tr>
<tr id="myRow2">
<td id="#R2C1">
<input class="myCell">
</td>
<td id="#R2C2">
<input class="myCell">
</td>
<td id="#R2C3">
<input class="myCell">
</td>
<td id="#R2C4">
<input class="myCell">
</td>
</tr>
<!-- ...and so on. -->
</table>
Having this table, when some event is triggered,I make this code run:
var rows = 1; // This value is updated when adding/removing a line
//This code runs from any <tr> by event keyup
if (event.altKey) { // I define here all Alt+someKey actions.
// Getting position values
var currentId = $(this).attr('id');
var row = Number(currentId.split('C')[0].substring(1));
var column = Number(currentId.split('C')[1]);
var belowVal;
if (event.which == 66) { //Case Ctrl+B
// If not the last row, start looping
if (rows > row) {
var diff = rows - row;
// Iteration over rows below
for (var i = 0; i < diff; i++) {
// Iteration over each column
for (var c = 1; c <= 4; c++) {
// here I try to get the value from column below
belowVal = $('#R'+(row+1+i).toString() +
'C'+c.toString()).val();
$('#R'+(row+i).toString()+'C' +
c.toString()).find('.myCell').val(belowVal);
}
}
}
$('#myRow'+rows.toString()).empty();
$('#myRow'+rows.toString()).remove();
rows--;
}
}
It works fine for removing the last row, but, when trying to remove an upper row, the values of current row and the ones below become blank instead of moving up. I made this code for each row below to pass it's values to the upper row, but it isn't doing what I wanted.
Why is this happening? I couldn't figure it out.
The problem seem to be, that the ids you are using to access the values are not the ids of the input elements, but rather the ids of the containing table cells.
Here an approach, which doesnt use the ids, but relies on the nodes structure instead, code not tested:
if (event.which == 66) {
var currentrow = $(this);
var currentinputs = currentrow.find('input.myCell');
while(var nextrow = currentrow.next('tr')) {
var nextinputs = nextrow.find('input.myCell');
currentinputs.each(function(index,element){
element.val(nextinputs.get(index).val());
});
currentrow = nextrow;
currentinputs = nextinputs;
}
currentrow.remove();
}
RESOLVED
Thanks to #JHoffmann, I was able to resolve my problem like this:
for (var c = 1; c <= 4; c++) {
// here I try to get the value from column below
belowVal = $('#R'+(row+1+i).toString()+'C'+c.toString())
.find('.myCell').val();
$('#R'+(row+i).toString()+'C'+c.toString())
.find('.myCell').val(belowVal);
}
In the line that assigns a value to belowVal, I forgot to call the method .find('.myCell') before calling .val(). That was the mistake that caused my code to fail, as #JHoffmann commented in his answer.
I have a form which displays multiple rows from database with 4 columns. From these record I need to write a new value in 4th column and update database record. But whenever I try, only First Row value can be updated/read. But not the other rows!! This can be due to the same "name=redirection" as it is given to each from "for loop". So, how can I get the values from other rows too??
for (int i=0; i<domains.size(); i++) {
domainprops = (String[]) domains.get(i);
%>
<table cellspacing="0" cellpadding="10" border="0" class="tableview" width="100%">
<td width="150"><input type="text" id="domains" name="domains" value="<%=domainprops[0]%>"></td>
<td width="160"><input type="text" name="defaulturl" value="<%=domainprops[1]%>" size="30"></td>
<td width="160"><input type="text" name="redirecturl" value="<%=domainprops[2]%>" size="30"></td>
<td width="160"> <input type="text" id="redirection" name="redirection"></td>
<td align="right"><a href="javascript:win2('recordUpdate.jsp?domains=<%=domainprops[0]%>
')">[Update]</a></td>
</tr>
</table>
<% } %>
Javascript Code :
function win2(urlPath) {
var winl = (screen.width-200)/2;
var wint = (screen.height-100)/2;
var settings = 'height=100,width=200,directories=no,resizable=no,status=no,scrollbars=no,menubar=no,location=no,top=' + wint + ',left=' + winl;
var changeurls=document.getElementById("redirection").value;
urlPath+='&rdirect='+changeurls
editWin.focus();
}
An ID in the DOM is supposed to be unique. If any element in the DOM has an ID, it should not be shared by any other element.
What I would suggest doing is appending your loop counter on to the end of the ID. This will ensure that every element you create in the DOM has its own unique ID.
for (int i=0; i<domains.size(); i++) {
domainprops = (String[]) domains.get(i);
...
<input type="text" id="domains_<%= i %>" name="domains" value="<%=domainprops[0]%>">
...
<input type="text" id="redirection_<%= i %>" name="redirection"></td>
</tr>
</table>
}
Next, pass the loop counter to the win2 function call:
<td align="right"><a href="javascript:win2('recordUpdate.jsp?domains=<%=domainprops[0]%>
', <%= i %>)">[Update]</a></td>
Finally, adjust the function itself...
function win2(urlPath, loopID) {
...
var changeurls=document.getElementById("redirection_" + loopID).value;
urlPath+='&rdirect='+changeurls
...
}
EDIT: Please read the answer referring to having multiple elements with the same ID. You should not be using multiple of the same ID.
You could use Javascript to iterate over redirection form elements.
function loopThroughRedirection(form) {
var result = "";
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name == 'redirection') {
// Do something to retrieve the value of redirection
result += form.elements[i].value
}
}
return result;
}
How can we Dynamically delete the html table rows using javascript.
We have a check box on each row. While clicking the remove button with the check box selected the row would be deleted. Such as
document.getElementById(j).innerHTML = '';
Removing an element is best done with DOM node functions like removeChild, rather than innerHTML-hacking. eg.:
function removeAllRowsContainingCheckedCheckbox(table) {
for (var rowi= table.rows.length; rowi-->0;) {
var row= table.rows[rowi];
var inputs= row.getElementsByTagName('input');
for (var inputi= inputs.length; inputi-->0;) {
var input= inputs[inputi];
if (input.type==='checkbox' && input.checked) {
row.parentNode.removeChild(row);
break;
}
}
}
}
Here's a small mockup on how this could be done:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Mockup</title>
<script type="text/javascript">
function killRow(src) {
var dRow = src.parentElement.parentElement;
document.all("table").deleteRow(dRow.rowIndex);
}
</script>
</head>
<body>
<form action="something.html">
<table id="table">
<tr>
<td><input type='checkbox' onclick='killRow(this);'>Click me!</td>
<td>Demodata 1</td>
</tr>
<tr>
<td><input type='checkbox' onclick='killRow(this);'>Click me!</td>
<td>Demodata 2</td>
</tr>
</table>
</form>
</body>
</html>
Key in this is a JScript-function which then can be used from any row in there. It might even be more generalized. When clicking on the checkboxes the function is called.
I'd rather not use innerHTML on this, I'd prefer DOM nodes (here parentElement).
Here is a function that performs the required action of deleting rows by checking the value of checkbox. Call this function in the onclick event of the delete button(Comments included). Hope this helps :)
function removeSampleRow(id) {
/***We get the table object based on given id ***/
var objTable = document.getElementById(id);
/*** Get the current row length ***/
var iRow = objTable.rows.length;
/*** Initial row counter ***/
var counter = 0;
/*** Performing a loop inside the table ***/
if (objTable.rows.length > 1) {
for (var i = 0; i < objTable.rows.length; i++) {
/*** Get checkbox object ***/
var chk = objTable.rows[i].cells[0].childNodes[0];
if (chk.checked) {
/*** if checked we del ***/
objTable.deleteRow(i);
iRow--;
i--;
counter = counter + 1;
}
}
/*** Alert user if there is now row is selected to be deleted ***/
if (counter == 0) {
alert("Please select the row that you want to delete.");
}
}else{
/*** Alert user if there are no rows being added ***/
alert("There are no rows being added");
}
}