Counting rows on a particular table - javascript

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');
...
});

Related

One extra radio button is getting printed in div in JQUERY

I'm trying to copy one row of a table and append a radio button to it. There are 3 rows that i declared in the html and an add button in jquery which can add names to the table. All of these rows are appended with a delete button. when I click the start button I want the names to go to the next div without the delete button and append a radio button to it. and the user should be able to vote the names.when i add names, an extra radio button without name value is passed to the div. I can't figure out why. I'm trying to make a voting system using jquery without using any databases(temporary). Please help. I can't figure out why the extra radio button is getting passed. It's only passed when i add candidate using the add button.
here's my code:
$(document).ready(function()
{
$('#start').click(function()
{
$("#div1").hide();
$("#buttonset1").hide();
$("#div2").show();
$("#voterName").val("")
if( $('#candidateTable thead tr').children().length = 1)
{
if( $('#newTable thead').children().length == 0 )
{
$('#newTable thead').append('<tr></tr>');
}
$('#newTable thead tr').append('<th>' + $($('#candidateTable thead tr').children()).text() + '</th>');
$('#candidateTable tbody tr').each(function(i)
{
if( $('#newTable tbody').children().length != $('#candidateTable tbody').children().length)
{
$('#newTable tbody').append('<tr></tr>');
}
$('#newTable tbody tr:nth-child(' + (i + 1) + ')').append('<td>' + $($(this).children()[0]).text()+'</td>'+'<td><input type="radio" class="radiobutton"></td>');
});
}
});
//delete candiates
$("#candidateTable").on('click', '.del', function()
{
$(this).closest('tr').remove();
});
//add candidate
$("#add").click(function()
{
//adding candidates
var candidatename = $("#candidatename").val();
if(candidatename.length!=0)
{
$("#candidateTable tbody").append('<tr><td>'+ candidatename +'</td>'+'<td>'+'<button class="del" id="Delete">Delete</button>'+'</td><tr>');
$("#candidatename").val('');
}
});
});
$(document).ready(function()
{
$("#final").click(function(){
$("#div2").hide();
$("#div4").show();
});
});
table, tr, th, td{
border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1> Voting System </h1>
<body>
<div id="div1">
<table id="candidateTable">
<thead>
<tr>
<th id="candidatelist">Candidate Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>XXXX</td>
<td><button class="del" id="Delete">Delete</button></td>
</tr>
<tr>
<td>YYYY</td>
<td><button class="del" id="Delete">Delete</button></td>
</tr>
<tr>
<td>ZZZZ</td>
<td><button class="del" id="Delete">Delete</button></td>
</tr>
</tbody>
</table>
</div>
<div id="buttonset1">
<br>
<br>
<input type="text" id="candidatename">
<button id="add">Add</button>
<br>
<br>
<button id="start">Start</button>
<br>
<br>
</div>
<br>
<form action="javascript:void(0)">
<div id="div2" style="display: none;">
<div id="buttonset2">
<label>Name</label>
<input type="text" name="Name" id="votername">
<button id="vote">Vote</button>
<br>
<br>
<table id="newTable">
<thead>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
</form>
<br>
<br>
<button id="final">Submit Votes</button>
</div>
</div>
<br>
<br>
<br>
<div id="div4" style="display:none;">
<h2>
Result
</h2>
</div>
</body>
</html>
Change this line of code:
$("#candidateTable tbody").append('<tr><td>'+ candidatename +'</td>'+'<td>'+'<button class="del" id="Delete">Delete</button>'+'</td><tr>');
with this:
$("#candidateTable tbody").append('<tr><td>'+ candidatename +'</td><td><button class="del" id="Delete">Delete</button></td></tr>');
in your add function. Now it will not add one extra row.
Full working example link is below
enter link description here

Storing count of table rows in a JS variable

I have some old code I am trying to poke through. This table is loaded via a Controller action returning a model, based off of a button click somewhere else in the page.
How can I find the number of rows in the table in a JS variable? I am terrible with JS. I have tried a few things and nothing has worked. Below is my code and also what I have tried to do to store the num of rows.
Table:
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
Here is what I have tried to do in JS:
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
console.log(rowId);
console.log(row);
Results from the console.log don't appear to be accurate. Anything helps. Thanks
Probably you want the number of rows of your table.
// javascript
var rowsInTable = document.getElementById("terminalReceipts").getElementsByTagName("tr").length;
//jquery
var rowsInTable2 = $("#customers").children('tbody').children('tr').length;
//if you need to do something with the rows:
var rows = $("#customers").children('tbody').children('tr');
rows.each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
you can also do that using jquery like this
var totalRowCount = $("#terminalReceipts tr").length; //this will give +1 row
var rowCount = $("#terminalReceipts td").closest("tr").length; //this will give actual row

docent display pop up with table id

When I click on my button "Select" it should show me the HTML popup, and for some reason is not happening.
Could it be some id problem or hard code?
The main idea is to click and bring some kind of list reading from a random array list.
Below: my .js with the call back id and display.
Any ideas?
<!-- This hosts all HTML templates that will be used inside the JavaScript code -->
<table class ="cls-{id} active-{active}" style="display: none;" width="100%" id="rowTemplate">
<tr class ="bb cls-{id} active-{active}">
<td class="active-{active}" id="{id}-question" width="70%">{question}</td>
<td class="cls-{id} active-{active}" width="30%">
<button class="buttons" step="0.01" data-clear-btn="false" style="background: #006b54; color:white !important ;" id="{id}-inspectionResult"></button>
</td>
</tr>
</table>
<div id="projectPopUp" class="popup-window" style="display:none">
<div class="popuptitle" id="details-name"></div>
<table width="100%" id="detailsgrid">
<tr>
<td style="text-align:left">Start Time</td>
<td> <select id="details-startTime" data-role="none"></select></td>
</tr>
<tr>
<td style="text-align:left">End Time</td>
<td> <select id="details-endTime" data-role="none"></select></td>
</tr>
</table>
<div>
<button class="smallButton" onClick="closeProjectPopup()">Cancel</button>
<button class="smallButton" onClick="submitProjectPopup()">Submit</button>
</div>
</div>
<table style="display: none;" id="sectionRowTemplate">
<tr width="100%" class="bb cls-{id}-row2 sectionheader">
<td class="cls-{id}" colspan="3">{question}</td>
</tr>
</table>
Javascript code:
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = i;
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: '',
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to show the popup
$('#projectPopUp').show();
//to close the popup
$('#projectPopUp').hide();
$(document).ready(function() {
buildQuestionnaire();
});

Code isn’t executed after removing rows in a table

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");
}

Trying to serialize a form with dynamically created input elements, but values of elements aren't posted

I am dynamically adding elements. However when I try and serialize the form, none of the dynamically generated elements are serialized.
This is the function I'm using to add elements to the page :
function addObjects(IDname,classname)
{
//to add more objects
var number;
switch(classname)
{
case "name":
number = no_Name++;
break;
case "part":
number = no_part++;
break;
}
var id = classname + number;
$("#"+IDname).append('<tr class="'+id+'"><td><input id="'+id+'" class="'+id+'" type="text"> <button class="'+id+'" onclick=removeAdditions("'+id+'")>x</button></td></tr>');
}
The page looks like this:
<html>
<head>
<script src="Controller.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//in order to prevent form reload when button click occurs
$(document).ready(function(){
document.getElementById("ReportForm").onsubmit = function (event) { event.preventDefault(); }
});
</script>
</head>
<body>
<div class="detailsPane" id="detailsPane1" >
<form id="ReportForm" name="ReportForm" >
<table style="width: 100%;">
<tbody>
<tr>
<td>
1. Describe the Status briefly-
</td>
<td>
<textarea id="StatDescp" name="StatDescp"></textarea>
</td>
</tr>
</tbody>
</table>
<br>
<table style="width: 100%;">
<thead>
<tr>
<th colspan="4" align="top">
Part Status
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="vertical-align:top;">
Part Name:
</td>
<td style="vertical-align:top;">
<table >
<tbody id="PartName">
<tr class="partname0">
<td><input class="part_name" type="text"> <button onclick='addObjects("PartName","part_name");'>+</button></td>
</tr>
</tbody>
</table>
</td>
<tbody>
</table>
</form>
</div>
<div id="buttonDiv" >
<a class="bottomLeftResultDiv" id="messageBox"></a>
<input type="button" id="saveButton" value="Save" style="width:85px" onclick="save();" />
</div>
</body>
</html>
And finally here is the save Button.
function save() {
var select = document.getElementById('newReportPane');
var contents = $('#ReportForm').serialize();
contents = contents.replace(/=on/g, "=checked");
contents = contents.replace(/\+/g, " ");
$("#messageBox").html("Saving report...");
console.log(contents);
$.post("/Report/Report1", { action: "save", content: contents }, function (data) {
if (data != "ACK")
$("#messageBox").html("Unable to save.");
else
$("#messageBox").html("Report saved successfully");
});
}
When I click on the save button, it only posts this StatDescp= without any of the dynamically generated elements.
I really can't figure out why.
Any help would be appreciated.
Give a name= attribute to each of your added inputs.
From http://api.jquery.com/serialize/
For a form element's value to be included in the serialized string,
the element must have a name attribute.

Categories

Resources