There is a table displaying model entries, with each field designated a unique div id combining a keyword and each row's ID. When the user enters a number in the table's input column, a script is supposed to: get the locations of the cells on the same row; and change the values of two predetermined cells based on the values of the other cells.
It seems that tests are successful until the final updating. I've tried using .val(), .value, and .html(), and the resultant cells go blank, or show 0 if the script is error-free. Would someone please post the correct jQuery command and why it works? Many thanks in advance.
The table:
<table id="dt_Positions" class="table table-striped">
<thead>
<tr>
<th class="text-center">Month</th>
<th class="text-center">Owed</th>
<th class="text-center">Bought</th>
<th class="text-center">Total Position</th>
<th class="text-center">Non-Fixed</th>
<th class="text-center">Fixed</th>
<th class="text-center">Fixed Position</th>
<th class="text-center">Proposed</th>
</tr>
</thead>
<tbody>
#if (Model.Forecasts.Any())
{
foreach (var record in Model.Summaries)
{
<tr>
<td id="nmonth#(record.fID)" align="center">#String.Format("{0:d}", #record.Month)</td>
<td id="ntotal#(record.fID)" align="center">#record.NTotal</td>
<td id="nbought#(record.fID)" align="center">#record.NBought</td>
<td id="ntposition#(record.fID)" align="center">#record.NTotalPosition</td>
<td id="nvariable#(record.fID)" align="center">#record.NVariable</td>
<td id="nfixed#(record.fID)" align="center">#record.NFixed</td>
<td id="nfposition#(record.fID)" align="center">#record.NFPosition</td>
<td id="ninput#(record.fID)" align="center"><input class="nInput" type="number" name="quantity" min="1" max="50000"></td>
</tr>
}
}
</tbody>
</table>
The script:
#section Scripts
{
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script type="text/javascript" language="javascript">
$(function () {
$('[id^=ninput]').keyup(function (e) {
var $id = $(this).attr('id');
var $i = $(this);
var $idNum = $id.slice(6);
var $tp = $('#ntposition' + $idNum);
var $fp = $('#nfposition' + $idNum);
var $nt = $('#ntotal' + $idNum);
var $nh = $('#nbought' + $idNum);
var $f = $('#nfixed' + $idNum);
//The lines below appear to be the hiccup
$tp.val($nh.val() + $i.html() - $nt.val());
$fp.val($nh.val() + $i.html() - $f.val());
debugger;
});
});
</script>
}
EDIT: Examples of ids returning "NaN" are:
ntotal = 29, nbought = 5, ntposition = -24, nvariable = 3, nfixed = 26, nfposition = -21, with all appearing to be int from testing the View, but ntotal, nbought, and nfixed showing "NaN" in the console.log and resulting in "NaN" appearing in the test View after an ninput = 5.
$i is the textbox, so to get its value you need to use $i.val(). The other elements are table cells, so to get or set the values you need .text(), not .val(). However you over complicating code by using id attributes. Instead, remove then and use relative selectors
$('input').keyup(function() { // or $('.nInput').keyup
var i = Number$(this).val());
var cells = $(this).closest('tr').children('td');
var tp = cells.eq(3);
var fp = cells.eq(6);
// Get current cell values as a number
var nt = Number(cells.eq(1).text());
var nh = Number(cells.eq(2).text());
var f = Number(cells.eq(5).text());
// Update totals
tp.text(nh + i - nt);
fp.text(nh + i - f);
});
Side note: The value of var i = $(this).val(); could be null but not sure how you want to handle this - possibly just use
var i = $(this).val();
if (!i) {
return; // don't do any calculations
}
You need to know the difference between val(), text() and html()
val() is for getting and setting values for form elements, input, select etc.
text() is for getting and setting plain unformatted text for non form elements.
html() is for getting and setting inner Html from a node
So what you want is:
$tp.text($nh.text() + $i.val() - $nt.text());
$fp.text($nh.text() + $i.val() - $f.text());
Also be careful as + is both mathematical addition and string concatenation in javascript so you may want to cast your parse the strings to the appropriate number type.
Related
I am creating a table using Google Firebase in JavaScript, but its not showing the table.
Here is my code:
User Table <!--function called on click on tab link-->
<table id="userTableInside" class="w3-table w3-centered w3-striped w3-card-2">
<tr style="background: #cccccc;">
<th>Institute Name</th>
<th>Role id</th>
<th>Institute id</th>
<th>Strikes</th>
<th>Status</th>
<!--<th>Perfomance Rating</th>-->
</tr>
<tr id="mytr">
</tr>
</table>
Added the src script tag above
<script>
//initialized firebase also
function tab1() {
var table= document.getElementById("userTableInside");
var i = 1;
var institudeId = sessionStorage.getItem("InstituteId");
var roleId = sessionStorage.getItem("RoleId");
var ref_1 = firebase.database.ref(institudeId + "/Admin/Usertable/");
ref_1.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var row= table.insertRows(i);
var x= row.insertCell(0);
var x1= row.insertCell(1);
var x2= row.insertCell(2);
x.innerHTML = childData.status;
x1.innerHTML = childData.totalTimeUsed;
x2.innerHTML = childData.report;
i++;
// ...
});
});
</script>
Everything seems fine to me, except the snapshot.forEach. Before using the values in the snapshot, First extract the values from the snapshot using snapshot.val().
Use snapshot.val().forEach. Hope this will solve your problem.
Note:
The listener receives a snapshot that contains the data at the specified location in the database at the time of the event. You can retrieve the data in the snapshot with the val() method.
I didn't check the table insertion logic as i found that snapshot is used directly.
You need to append the data to the table
$("#userTableInside > tbody").append("" + data for col 1 + "" + data for col 2 + "" + data for col 3 + "");
use the proper variable instead of "data for col 1" etc.
make sure you end with a to indicate the end of the table row.
Do this for each time you loop thru your "children" - basically just replace your code in the same place
I have the following HTML table:
<table id="review-total">
<tbody><tr class="wlp">
<td class="left-cell">WLP Total</td>
<td>199.00</td>
</tr>
<tr class="tax">
<td class="left-cell">GST</td>
<td>19.90</td>
</tr>
<tr class="net">
<td class="left-cell">Order Total</td>
<td class="net-price">$218.90</td>
</tr>
</tbody>
</table>
I'm trying to loop through this table and retrieve the values i.e
199.00, 19.90 and $218.90 I have the following code:
var reviewTotal = document.getElementById('review-total');
for (var i = 1; i < reviewTotal.rows.length; i++) {
if (reviewTotal.rows[i].cells.length) {
wlpTotal = (reviewTotal.rows[i].cells[1].textContent.trim());
gstAmount = (reviewTotal.rows[i].cells[3].textContent.trim());
totalOrderAmount = (reviewTotal.rows[i].cells[5].textContent.trim());
}
}
I'm having a small issue trying to retrieve those values specified above, at present the error I get is textContent is undefined.
Can someone show me how I should go about retrieving those values, unfortunately I'm not strong in Javascript.
You have 3 rows and each row has only 2 cells. The 3 and 5 indices are undefined and undefined doesn't have .textContent property.
If you want to store the values by using specific variable names, you remove the loop and select the target elements manually:
var wlpTotal = reviewTotal.rows[0].cells[1].textContent.trim();
var gstAmount = reviewTotal.rows[1].cells[1].textContent.trim();
var totalOrderAmount = reviewTotal.rows[2].cells[1].textContent.trim();
If you want to store the values in an array, you can code:
var values = [].map.call(reviewTotal.rows, function(row) {
return row.cells[1].textContent.trim();
});
By using ES2015's Destructuring Assignment you can also extract the array's elements:
var [wlpTotal, gstAmount, totalOrderAmount] = values;
First:the index start the 0 either row or cell.
Secend:get value in the tag to use innerText or innerHTML ,The code following:
var reviewTotal = document.getElementById('review-total');
for (var i = 0; i < reviewTotal.rows.length; i++)
{
if (reviewTotal.rows[i].cells.length>1)
{
wlpTotal = (reviewTotal.rows[i].cells[1].innerText);
}
}
I just started using DataTables and everything works fine when creating the table.
When I display 5, 24, 47 rows in my table, DataTables behaves as I would expect.
But I have this table that has around 700 rows and I get the error in Google Chrome,
"VM9075 dataTables.min.js:24Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined "
and in IE 9,
"SCRIPT5007: Unable to set value of the property '_DT_CellIndex': object is null or undefined
jquery-1.10.2.min.js, line 4 character 2367"
I don't have jQuery included twice btw.
I'm not sure how to proceed from here.
I tried to use the unminified version of the .js file to debug it more myself but i kept getting an "ext" method or property is undefined and couldn't fix that either.
Any help is appreciated!
I figured it out
The biggest issue was not knowing exactly what this error actually meant.
In my case it meant "the number of every <td> element in your table that is a child of a <tr> element doesn't match the number of <th> elements that are a child of the <thead> element."
My table was being generated by the server, and some of the <tr> elements had 27 <td> children (which was filling the whole width of the table up, but some of the <tr> elements only had 3, 4, or 5, ... <td> child elements which isn't a valid table.
I solved it by adding empty <td> elements in my table for the <tr> elements that lacked the correct number of <td> elements
var makeTableValidObject = {
thisWasCalled: 0,
makeTableValid: function() {
var tableToWorkOn = document.getElementById("table1");
//check the number of columns in the <thead> tag
//thead //tr //th elements
var numberOfColumnsInHeadTag = tableToWorkOn.children[1].children[0].children.length;
var numberOf_trElementsToValidate = tableToWorkOn.children[2].children.length;
//now go through each <tr> in the <tbody> and see if they all match the length of the thead columns
//tbody //all trs//all tds elements
//tableToWorkOn.children[2].children.children);
for(var i = 0; i < numberOf_trElementsToValidate; i++) {
//row my row make sure the columns have the correct number of elements
var tdColumnArray = tableToWorkOn.children[2].children[i].children
var trElementToAppendToIfNeeded = tableToWorkOn.children[2].children[i];
if(tdColumnArray.length != numberOfColumnsInHeadTag) {
//since they don't match up, make them valid
if(tdColumnArray.length < numberOfColumnsInHeadTag) {
//add the necessary number of blank <td> tags to the <tr> element to make this <tr> valid
var tdColumnArrayLength = tdColumnArray.length;
for(var j = 0; j < (numberOfColumnsInHeadTag - tdColumnArrayLength); j++) {
var blank_tdElement = document.createElement("td");
blank_tdElement.id = "validating_tdId" + i + "_" + j;
trElementToAppendToIfNeeded.appendChild(blank_tdElement);
}
}
else {
//TODO: remove <td> tags to make this <tr> valid if necessary
}
}
}
}
};
Edit 1:
It has been awhile and this question is still getting a bunch of views. I have since updated the code.
I replaced the first line of code with the second line to be more general
var numberOfColumnsInHeadTag = tableToWorkOn.children[1].children[0].children.length;
var numberOfColumnsInHeadTag = tableToWorkOn.querySelectorAll('thead')[0].querySelectorAll('th');
Pretty much where ever in the prior code you see the children.children I replaced that with the querySelectorAll(...) Function.
It uses css selectors which makes it amazingly powerful.
stay blessed
Ran into this same issue and implemented this same solution (essentially) in jquery based on Coty's. Hope this helps someone. :)
$( '.table' ).each(function( i ) {
var worktable = $(this);
var num_head_columns = worktable.find('thead tr th').length;
var rows_to_validate = worktable.find('tbody tr');
rows_to_validate.each( function (i) {
var row_columns = $(this).find('td').length;
for (i = $(this).find('td').length; i < num_head_columns; i++) {
$(this).append('<td class="hidden"></td>');
}
});
});
As answered by Coty, the problem lies in the mismatch of td elements generated in the header and body of table.
I'd like to highlight one of the reasons why it can occur (For .Net Users).
If Page numbers are being displayed at the end of gridview, they can disrupt table structure.
Remove AllowPaging="true" from your gridview to solve this.
And no worries because Datatable handles Paging.
you always keep four column but sometimes you will receive or append null td or only one td, td count always match with total column so when you does not have record then make td as following.
<th>No</th>
<th>Name</th>
<th>place</th>
<th>Price</th>
----------------------------------------
<td colspan="4">Data not found.</td>
<td style="display: none;"></td>
<td style="display: none;"></td>
<td style="display: none;"></td>
this error can also be triggered if you try to set options for the responsive extension for more columns than you have.
$( '.table' ).each(function( i ) {
var worktable = $(this);
var num_head_columns = worktable.find('thead tr th').length;
var rows_to_validate = worktable.find('tbody tr');
rows_to_validate.each( function (i) {
var row_columns = $(this).find('td').length;
for (i = $(this).find('td').length; i < num_head_columns; i++) {
$(this).append('<td class="hidden"></td>');
}
});
});
I am trying to attach a row to an editable table using data from an array. In order to do this, I'm adding a row, then utilizing a save feature in order to manipulate the s of the row. My HTML table is:
<table id="tblData" class="table table-hover">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Treatment Number</th>
<th>Cell Number</th>
<th>Waste Container Number</th>
</tr>
</thead>
<tbody></tbody>
</table>
Being that the array data will be entered into the most recently added row, I've just accessed that using the code below, however now I am struggling to access the actual cells. My current code is:
function UpSave(rowData) {
var tblData = document.getElementById("tblData");
var lastRow = tblData.rows[tblData.rows.length - 1 ];
var tdDate = lastRow.children("td:nth-child(1)");
var tdTime = lastRow.children("td:nth-child(2)");
var tdTreatmentNum = lastRow.children("td:nth-child(3)");
var tdCellNum = lastRow.children("td:nth-child(4)");
console.log(par);
var tdWasteContNum = lastRow.children("td:nth-child(5)");
var tdButtons = lastRow.children("td:nth-child(6)");
tdDate.html(tdDate.children(data[rowData][0]));
tdTime.html(tdTime.children(data[rowData][1]));
tdTreatmentNum.html(tdTreatmentNum.children(data[rowData][2]));
tdCellNum.html(tdCellNum.children(data[rowData][3]));
tdWasteContNum.html(tdWasteContNum.children(data[rowData][4]));
tdButtons.html("<img src='trash.png' class='btnDelete'><img src='pencil.png' class='btnEdit'><img src='up.png' class='btnUp'><img src='down.png' class='btnDown'>");
};
but the .children at the end of the variables are not valid. Any ideas on what to have instead in order to access those cells in the row?
(data is the array containing the text I'm putting into the )
It looks like you never clearly defined the variable tblData by leaving out quotations when you do your original getElementById. Add this to Replace the first line in the function:
var tblData = document.getElementById("tblData");
Adding the quotations will bind the table in the DOM to the variable, then you can do the rest of the stuff.
Revised answer using jQuery:
var $tblData = $("#tblData");
var $lastRow = $tblData.find('tr').last();
var $tdDate = $lastRow.find('td').eq(1);
var $tdTime = $lastRow.find('td').eq(2);
var $tdTreatmentNum = $lastRow.find('td').eq(3);
var $tdCellNum = $lastRow.find('td').eq(4);
//console.log(par);
var $tdWasteContNum = $lastRow.find('td').eq(5);
var $tdButtons = $lastRow.find('td').eq(6);
$tdDate.html(data[rowData][0]);
$tdTime.html(data[rowData][1]);
$tdTreatmentNum.html(data[rowData][2]);
$tdCellNum.html(data[rowData][3]);
$tdWasteContNum.html(data[rowData][4]);
$tdButtons.html("<img src='trash.png' class='btnDelete'/><img src='pencil.png' class='btnEdit'/><img src='up.png' class='btnUp'/><img src='down.png' class='btnDown'/>");
But, if you still want to use pure javascript, try changing the
.children("td:nth-child(x)");
to
.childNodes[x];
Edit note: I changed the inside of the .html(...) function calls so just use the array directly. Previously I had just copy/pasted the OP code for that portion.
I've been struggling with this issue for a while now. Maybe you can help.
I have a table with a checkbox at the beginning of each row. I defined a function which reloads the table at regular intervals. It uses jQuery's load() function on a JSP which generates the new table.
The problem is that I need to preserve the checkbox values until the user makes up his mind on which items to select. Currently, their values are lost between updates.
The current code I use that tries to fix it is:
refreshId = setInterval(function()
{
var allTicks = new Array();
$('#myTable input:checked').each(function() {
allTicks.push($(this).attr('id'));
});
$('#myTable').load('/get-table.jsp', null,
function (responseText,textStatus, req ){
$('#my-table').tablesorter();
//alert(allTicks + ' length ' + allTicks.length);
for (i = 0 ; i < allTicks.length; i++ )
$("#my-table input#" + allTicks[i]).attr('checked', true);
});
}, $refreshInterval);
The id of each checkbox is the same as the table entry next to it.
My idea was to store all the checked checkboxes' ids into an array before the update and to change their values after the update is done, as most of the entries will be preserved, and the ones that are new won't really matter.
'#myTable' is the div in which the table is loaded and '#my-table' is the id of the table which is generated. The checkbox inputs are generated along with the new table and with the same ids as before.
The weird thing is that applying tablesorter to the newly generated table works, but getting the elements with the stored ids doesn't.
Any solutions?
P.S: I know that this approach to table generation isn't really the best, but my JS skills were limited back then. I'd like to keep this solution for now and fix the problem.
EDIT:
Applied the syntax suggested by Didier G. and added some extra test blocks that check the status before and after the checkbox ticking.
Looks like this now:
refreshId = setInterval(function()
{
var allTicks = []
var $myTable = $('#my-table');
allTicks = $myTable.find('input:checked').map(function() { return this.id; });
$('#myTable').load('/get-table.jsp', null,
function (responseText,textStatus, req ){
$myTable = $('#my-table');
$('#my-table').tablesorter();
var msg = 'Before: \n';
$myTable.find('input').each(function(){
msg = msg + this.id + " " + $(this).prop('checked') + '\n';
});
//alert(msg);
//alert(allTicks + ' length ' + allTicks.length);
for (i = 0 ; i < allTicks.length; i++ ){
$myTable.find('#' + allTicks[i]).prop('checked', true);
}
msg = 'After: '
$myTable.find('input').each(function(){
msg = msg + this.id + " " + $(this).prop('checked') + '\n';
});
//alert(msg);
});
}, $refreshInterval);
If I uncomment the alert lines, and check 2 checkboxes, on the next update I get (for 3 row table):
Before: host2 false
host3 false
host4 false
object [Object] length 2
After: host2 false
host3 false
host4 false
Also did a previous check on the contents of the array and it has all the correct entries.
Can the DOM change or working with an entirely new table instance be a cause of this?
EDIT2:
Here's a sample of the table generated by the JSP (edited for confidentiality purposes):
<table id="my-table" class="tablesorter">
<thead>
<tr>
<th>Full Name</th>
<th>IP Address</th>
<th>Role</th>
<th>Job Slots</th>
<th>Status</th>
<th>Management</th>
</tr>
</thead>
<tbody>
<tr>
<td>head</td>
<td>10.20.1.14</td>
<td>H</td>
<td>4</td>
<td>ON</td>
<td>Permanent</td>
</tr>
<tr>
<td>
<input type="checkbox" id="host2" name="host2"/>
host2
</td>
<td>10.20.1.7</td>
<td>C</td>
<td>4</td>
<td>BSTART</td>
<td>Dynamic</td>
</tr>
<tr>
<td><input type="checkbox" id="host3" name="host3"/>
host3</td>
<td>10.20.1.9</td>
<td>C</td>
<td>4</td>
<td>BSTART</td>
<td>Dynamic</td>
</tr>
<tr>
<td><input type="checkbox" id="host4" name="host4"/>
host4</td>
<td>10.20.1.11</td>
<td>C</td>
<td>4</td>
<td>BSTART</td>
<td>Dynamic</td>
</tr>
</tbody>
</table>
Note that the id and name of the checkbox coincide with the host name. Also note that the first td does not have a checkbox. That's the expected behavior.
Changing 'special' attributes like disbaled or checked should be done like this:
$(...).attr('checked','checked');
or this way if you are using jQuery 1.6 or later:
$(...).prop('checked', true); // more reliable
See jQUery doc about .attr() and .prop()
Here's your piece of code modified with a few optimizations (check the comments):
refreshId = setInterval(function()
{
var allTicks = [],
$myTable = $('#myTable'); // select once and re-use
// .map() returns an array which is what you are after
// also never do this: $(this).attr('id').
// 'id' is a property available in javascript and
// in .map() (and in .each()), 'this' is the current DOMElement so simply do:
// this.id
allTicks = $myTable.find('input:checked').map(function() { return this.id; });
$myTable.load('/get-table.jsp', null, function (responseText,textStatus, req ) {
$myTable.tablesorter();
//alert(allTicks + ' length ' + allTicks.length);
for (i = 0 ; i < allTicks.length; i++ )
// avoid prefixing with tagname if you have the ID: input#theId
// #xxx is unique and jquery will use javascript getElementById which is super fast ;-)
$myTable.find('#' + allTicks[i]).prop('checked', true);
});
}, $refreshInterval);
Let us assume that the JavaScript does retrieve and set the checkboxes ticks.
Then there still is a problem with the asynchrone Ajax call.
First try it with a very large $refreshInterval.
Place the for-loop before the tablesorter call.
Do not setInterval, but setTimeout and schedule this for one single time.
Then in the load function schedule the next time.
This prevents overlapping calls which were a possible cause for the error.
But may stop refreshing, when the load is not called. (Not so important.)
After lots of painful hours of digging up every small detail, I realized that my problem was not how I coded the thing, nor was it stuff like unexpected DOM changes, but a simple detail I failed to see:
The id I was trying to assign to the checkbox contained a period (".") character.
This causes lots of problems for jQuery when trying to look up that sort of id, because a period as-is acts as a class descriptor. To avoid this, the period character must be escaped using 2 backslashes.
For example:
$("#my.id") // incorrect
$("#my\\.id") // correct
So then the fix in my case would be:
$myTable.find('#' + allTicks[i].replace(".", "\\.")).prop('checked', true);
... and it finally works.
Thanks everyone for all your helping hands!