There are lots of examples on the internet, including SO, telling people how to loop through the rows of a table and get the values using Javascript or Jquery. Unfortunately, none of these examples work for me:
JavaScript:
var table = document.getElementById("tbInvoiceDetails");
var rowLength = table.rows.length;
for (var i = 0; i < rowLength; i += 1) {
var row = table.rows[i];
var cell = row.cells[10].innerHTML;
}
This gets:
<input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Vat" value="0" type="hidden">0
How can I get the value (=0) from this?
JQuery:
$("#tbInvoiceDetails tr").each(function () {
//Code
}
This simply does not work. I have tried every combination I can think of inside the "" and nothing works.
Table HTML with One Line:
<tbody id="tbInvoiceDetails">
<tr id="trInvoiceDetail0">
<td style="display:none">
<input name="InvoiceDetails.Index" value="0" type="hidden"></td>
<td style="display:none"><input name="InvoiceDetails[0].id" value="-1" type="hidden"></td>
<td style="display:none"><input name="InvoiceDetails[0].InvoiceId" value="0" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].LineTypeId" value="1" type="hidden">1</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].AllocationCodeId" value="19" type="hidden">2030 6016750 KQ73020394 11014008</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].GspId" value="" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].RunTypeId" value="" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].BillingPeriodFromDate" value="06/08/2015" type="hidden">06/08/2015</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].BillingPeriodToDate" value="19/08/2015" type="hidden">19/08/2015</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Net" value="9999" type="hidden">9999</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Vat" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].InterestPay" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].InterestReceiveable" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].VatCodeId" value="8" type="hidden">8</td>
<td><input class="btn" id="btnRemoveInvoiceDetail" value="Remove" onclick="removeRow(0);" type="button"></td>
</tr>
</tbody>
Going the by-column-position route:
jQuery:
$('#tbInvoiceDetails tr td:nth-child(11) input').each(
function() {
var val = this.value;
console.log(val);
}
);
Pure JS:
var table = document.getElementById("tbInvoiceDetails");
var rowLength = table.rows.length;
for (var i = 0; i < rowLength; i += 1) {
var input = table.rows[i].cells[10].firstElementChild;
var val = input.value;
console.log(val);
}
Related
I have an html table that has 5 columns. 2 columns are checkboxes (entry and high) and the other 3 are data. I have 2 buttons, one is called entry and the other high. When a user clicks on the high button, I'm trying to check the column (high) only and get all that is checked, take those values and average them.
The same with entry, when the entry button is clicked, check only the checkboxes in column (entry) and take those values and average them.
So far I have a function to check both columns but not sure how to separately check and separate the columns to each button function only. I have tried the below, but the GetHigh function doesn't work.
Any points in the right direction would be appreciated!
Table
<td><input type="checkbox" class="entry" id="entry" value="{{$sup->entry}}" name="rows[]"></td>
<td><input type="checkbox" class="high" id="high" value="{{$sup->high}}" name="rows[]"></td>
<td><span style="color: #007E33">{{$sup->entry}} </span></td>
<td><span style="color: #007E33">{{$sup->high}} </span></td>
<td><span style="color: #007E33">{{$sup->days}} </span></td>
Buttons
<a href="#here" class="btn btn-primary btn-pill w-10" id="entry" onclick="GetEntry()">
Entry Average
</a>
<a href="#here" class="btn btn-primary btn-pill w-10" id="high" onclick="GetHigh()">
High Average
</a>
Javascript
function GetEntry() {
//Create an Array.
var selected = new Array();
//Reference the Table.
var supTable = document.getElementById("supTable");
//Reference all the CheckBoxes in Table. I WANT ONLY THE ENTRY COLUMN
var entry = supTable.getElementsByTagName("INPUT");
// Loop and push the checked CheckBox value in Array.
for (var i = 0; i < entry.length; i++) {
if (entry[i].checked) {
selected.push(entry[i].value);
}
}
// alert("Average: " + calculate(selected));
$(".text-message").text("Average: " + calculate(selected)).show();
}
function GetHigh() {
//Create an Array.
var selected = new Array();
//Reference the Table.
var supTable = document.getElementById("supTable");
//Reference all the CheckBoxes in Table. I WANT ONLY THE ENTRY COLUMN
var entry = supTable.getElementsByName("High");
// Loop and push the checked CheckBox value in Array.
for (var i = 0; i < high.length; i++) {
if (high[i].checked) {
selected.push(high[i].value);
}
}
// alert("Average: " + calculate(selected));
$(".text-message").text("Average: " + calculate(selected)).show();
}
getElementsByName is used to select HTML where their name="" attribute matches what you've entered, in this case 'High'. But your HTML in the example shows a different name.
You want to use querySelectorAll('high') to get all of the elements that have class="high" set.
You can use a css selector to get the cells of your table
const getCheckboxes = columnIndex =>document.querySelectorAll(`tbody td:nth-child(${columnIndex}) input:checked`);
Or add a common class and select by the class to the checkboxes
const getCheckboxes = className =>document.querySelectorAll(`tbody .${className}:checked`);
Basic example:
const getCheckedCheckboxesClassName = className => document.querySelectorAll(`tbody .${className}:checked`);
const getCheckedCheckboxesByIndex = columnIndex =>document.querySelectorAll(`tbody td:nth-child(${columnIndex}) input:checked`);
const sumValues = cbs => [...cbs].reduce((total, cb) => total + +cb.value, 0);
const getTotal = (group) => {
const cbs = getCheckedCheckboxesClassName(group);
const value = sumValues(cbs);
console.log(value);
}
const getTotalIndex = (index) => {
const cbs = getCheckedCheckboxesByIndex(index);
const value = sumValues(cbs);
console.log(value);
}
<button type="button" onclick="getTotal('low'); getTotalIndex(1)">low</button>
<button type="button" onclick="getTotal('high'); getTotalIndex(2)">high</button>
<table>
<tbody>
<tr>
<td><input class="low" type="checkbox" value="1" /></td>
<td><input class="high" type="checkbox" value="10" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="2" /></td>
<td><input class="high" type="checkbox" value="20" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="3" /></td>
<td><input class="high" type="checkbox" value="30" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="4" /></td>
<td><input class="high" type="checkbox" value="40" /></td>
</tr>
<tr>
<td><input class="low" type="checkbox" value="5" /></td>
<td><input class="high" type="checkbox" value="50" /></td>
</tr>
</tbody>
</table>
I wrote an html table filled with inputs. How could I use JavaScript to check if no more than 5 numbers were entered per line.
This is an example row
<table id="mytable" onchange="xxx()">
<tr>
<td><input type="number" name="num1-1" min="1" max="10" ></td>
<td><input type="number" name="num2-1" min="11" max="20" ></td>
<td><input type="number" name="num3-1" min="21" max="30" ></td>
<td><input type="number" name="num4-1" min="31" max="40" ></td>
<td><input type="number" name="num5-1" min="41" max="50" ></td>
<td><input type="number" name="num6-1" min="51" max="60" ></td>
<td><input type="number" name="num7-1" min="61" max="70" ></td>
<td><input type="number" name="num8-1" min="71" max="80" ></td>
<td><input type="number" name="num9-1" min="81" max="90" ></td>
</tr>
</table>
Try something like this:
function xxx() {
// Get table element
let table = document.getElementById("mytable");
// Get table rows
let rows = table.rows;
let bool = false;
// Go over rows
for(i = 0; i < rows.length; i++) {
// Get cells of current row
const columns = rows[i].cells;
let count = 0;
// Go over current row's cells
for(j = 0; j < columns.length; j++) {
// Count a cell if it has a value
if(columns[j].children[0].value != "") {
count++;
}
}
bool = count <= 5;
}
console.log(bool);
}
The function prints true if all rows have no more than 5 values per line.
I want to add new rows having 3 input field and check if multiplication of 2 field equals to third input field. But my problem is if I check the multiplication of first 2 input field, the result will effect second row and third row etc because they all have same id and user can add many rows.
How to check with different id or without effected. my some code are as follows:
function addRow(elem,id) {
var trElement = elem.parentElement.parentElement;
var tr = document.getElementsByTagName('tr');
tr = Array.prototype.slice.call(tr);
var a = tr.indexOf(trElement);
var b = a+1;
var table = document.getElementById('dataTable');
var j, m;
var rowCount = table.rows.length;
var row = table.insertRow(a);
var colCount = table.rows[b].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[b].cells[i].innerHTML;
}
}
<table width="100%" id="dataTable">
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
</table>
<input type="button" id="agri" value="Add Row" onclick="addRow(this,id)" />
Thanks in Advance
I hope it Help you ;
cheak result as :
function addRow(elem,id) {
var trElement = elem.parentElement.parentElement;
var tr = document.getElementsByTagName('tr');
tr = Array.prototype.slice.call(tr);
var a = tr.indexOf(trElement);
var b = a+1;
var table = document.getElementById('dataTable');
var j, m;
var rowCount = table.rows.length;
var row = table.insertRow(a);
var colCount = table.rows[b].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[b].cells[i].innerHTML;
}
}
function cheakMulti() {
r = document.getElementsByTagName('tr');
for (i = 0; i < r.length; i++)
{
if(r[i].children[2].children[0].value==r[i].children[1].children[0].value*r[i].children[0].children[0].value)
{
r[i].children[2].children[0].style.backgroundColor="green";
}
else
{
r[i].children[2].children[0].style.backgroundColor="red";
}
}
}
<table width="100%" id="dataTable">
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
<tr>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
<td><input name="" type="text" /></td>
</tr>
</table>
<input type="button" id="agri" value="Add Row" onclick="addRow(this,id)" />
<input type="button" id="agri" value="Cheak" onclick="cheakMulti(this,id)" />
I have some HTML that is being generated by some server-side code. The HTML that's generated looks like this:
<table id="myChoices">
<tr>
<td><input type="radio" name="choice" value="1" /></td>
<td>Monday</td>
<td>Mar 7</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="2" /></td>
<td>Tuesday</td>
<td>Mar 8</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="3" /></td>
<td>Wednesday</td>
<td>Mar 9</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="4" /></td>
<td>Thursday</td>
<td>Mar 10</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="5" /></td>
<td>Friday</td>
<td>Mar 11</td>
</tr>
</table>
When a user makes a choice, I need to get the two cells next to it. For example, if someone chooses the third option, I'm trying to get the following:
<td>Wednesday</td><td>Mar 9</td>
In my attempt to do this, I have the following jQuery:
function getHtml() {
var html = '';
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.parent().parent();
var cells = grandparent.children();
var html = '';
for (var i = 0; i < cells.length; i++) {
if (i > 0) {
var cellHtml = cells[i];
html += cellHtml;
}
}
}
return html;
}
Unfortunately, my approach is not working. When I do the following:
var test = getHtml();
console.log(test);
I see the following in the console window:
[object HTMLTableCellElement][object HTMLTableCellElement]
Why? How do I get the actual HTML string?
Use outerHTML, instead you are storing the jQuery object in the variable.
var cellHtml = cells[i];
should be
var cellHtml = cells[i].outerHTML;
JS
function getHtml() {
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.closest('tr'),
cells = grandparent.children();
var html = '';
for (var i = 1; i < cells.length; i++) {
html += cells[i].outerHTML + ' ';
}
}
return html;
}
js Fiddle
I propose you change the script a bit to simplify the process altogether.
$("#myChoices input").change( function() {
var string = $(this).parent().nextAll("td").text();
});
Variable "string" will contain the text you are looking for.
I believe you could just use something simple like:
$("input[type='radio']:checked").parents("tr").first().text();
Example: http://codepen.io/cchambers/pen/ONNawo
JSFIDDLE DEMO
Use this instead
var cellHtml = cells[i].outerHTML;
Complete JS
var html = '';
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.parent().parent();
var cells = grandparent.children();
var html = '';
for (var i = 0; i < cells.length; i++) {
if (i > 0) {
var cellHtml = cells[i].outerHTML; //change here
html += cellHtml;
}
}
}
console.log(html);
Result format:
<td>Monday</td><td>Mar 7</td>
The easiest way would be to use the .html() method on a dynamic tr which contains the other two td elements.
A trick is to clone them then wrap them in a tr and get the html of that
var others = $(this).closest('td').siblings().clone();
alert( others.wrapAll('<tr>').parent().html());
$(function(){
$('#myChoices [name="choice"]').on('change', function(){
var others = $(this).closest('td').siblings().clone();
alert( others.wrapAll('<tr>').parent().html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myChoices">
<tr>
<td><input type="radio" name="choice" value="1" /></td>
<td>Monday</td>
<td>Mar 7</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="2" /></td>
<td>Tuesday</td>
<td>Mar 8</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="3" /></td>
<td>Wednesday</td>
<td>Mar 9</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="4" /></td>
<td>Thursday</td>
<td>Mar 10</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="5" /></td>
<td>Friday</td>
<td>Mar 11</td>
</tr>
</table>
In a function form it would be
function getHtml() {
var item = $("#myChoices input[type='radio']:checked");
var otherTD = item.closest('td').siblings().clone();
return otherTD.wrapAll('<tr>').parent().html();
}
You could use jquery's siblings method:
var textContents = $("#myChoices input[type='radio']:checked").siblings().html();
I have a bunch of user input to store from a javascript from. I like to loop through some counter as it stores the input instead of assigning them one at a time. Is this the correct syntax to specify the element ID? It's not working for me at this point and complains for example catMaxInput: [Exception: ReferenceError: catMaxInput is not defined]
var catInput = [], catMaxInput = [], catCostSFHR = [], catOccHRStart=[], catOccHREnd =[];
var z = 1;
for (var i=0; i<3; i++){
catMaxInput[i] = (Math.round(parseFloat(document.getElementById("cat\"" + z + "\"Max").value)));
z++;
}
for (var c=0; c<3; c++){
catTotalArea[c] = (Math.round(parseFloat(document.getElementById("cat\"" + z + "\"TotalArea").value)));
z++;
}
So far this is the form:
<tr>
<td>CAT 1</td>
<td><input name="data1Max4" type="text" id="cat1Max" value="20" /></td>
<td><input name="data1Max7" type="text" id="cat1TotalArea" value="50,000 SF" /></td>
<td><input name="data1Max10" type="text" id="cat1CostSFHR" value="$ 100.00" /></td>
<td><input name="data1Max13" type="text" id="cat1OccHRStart" value="6:00am" /></td>
<td><input name="data1Max16" type="text" id="cat1OccHREnd" value="12:00pm" /></td>
</tr>
<tr>
<td>CAT B</td>
<td><input name="data2Max5" type="text" id="cat2Max" value="70" /></td>
<td><input name="data2Max8" type="text" id="cat2TotalArea" value="20,000 SF" /></td>
<td><input name="data2Max11" type="text" id="cat2CostSFHR" value="$ 50.00" /></td>
<td><input name="data2Max14" type="text" id="cat2OccHRStart" value="12:00pm" /></td>
<td><input name="data2Max17" type="text" id="cat2OccHREnd" value="8:00pm" /></td>
</tr>
<tr>
<td>CAT C</td>
<td><input name="data3Max6" type="text" id="cat3Max" value="100" /></td>
<td><input name="data3Max9" type="text" id="cat3TotalArea" value="30,000 SF" /></td>
<td><input name="data3Max12" type="text" id="cat3CostSFHR" value="$ 0.00" /></td>
<td><input name="data3Max15" type="text" id="cat3OccHRStart" value="8:00pm" /></td>
<td><input name="data3Max18" type="text" id="cat3OccHREnd" value="6:00am" /></td>
</tr>
The result of "cat\"" + i +"\"Max" is a string that has the value of i between ".
You proabably need this to be "cat" + i +"Max".
You are escaping and adding double quotes where you don't need to.
var catInput = [], catMaxInput = [], catCostSFHR = [],
catOccHRStart=[], catOccHREnd =[];
for (var i=0; i<3; i++){
catMaxInput[i] = (Math.round(parseFloat(
document.getElementById("cat" + i +"Max").value)));
}
for (var c=0; c<3; c++){
catTotalArea[c] = (Math.round(parseFloat(
document.getElementById("cat" + c+ "TotalArea").value)));
}
Replace:
getElementById("cat\"" + i +"\"Max")
getElementById("cat\"" + c+ "\"TotalArea")
with:
getElementById("cat"+i+"Max")
getElementById("cat"+c+"TotalArea")
Update: In ES6 you can do:
getElementById(`cat${i}Max`)
getElementById(`cat${c}TotalArea`)
There are better ways of doing this like:
How do I iterate through table rows and cells in javascript?