Just started JS.
I have a button and it calls a function which should loop through an array and show me each item but it doesn't. It says that:
showWorthSum() function is not defined.
function addWorth()
{
var table1= document.getElementById("tableNetWorths");
var rowCount1= table1.rows.length;
var row1= table1.insertRow(rowCount1);
var arr= [];
for(count = 0; count < rowCount1; count++)
{
arr.push(table1.rows[count].cells[1].innerHTML);
}
arr.shift();
return arr;
}
function showWorthSum()
{
var returnedArr= [];
returnedArr.push(addWorth());
var totalWorth= 0;
var arrCount= 10 ;
for(int count = 0; count < arrCount; count++)
{
//totalWorth= totalWorth+ returnedArr[count];
document.write(returnedArr[count]);
//debugger;
}
//return totalWorth;
}
Button:
<button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>
And yes I have taken care of script tags etc, just stripped those for the purpose of posting.
Update: (Full code)
<!DOCTYPE html>
<html>
<head>
<link href="css/basic.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script>
function alterTable()
{
//Textboxes code
var tBoxCompany= document.getElementById("txtboxCompany");
var tBoxAmount= document.getElementById("txtboxAmount");
//table code
var table= document.getElementById("tableNetWorths");
var rowCount= table.rows.length;
var row= table.insertRow(rowCount);
var Cell1= row.insertCell(0);
var Cell2= row.insertCell(1);
Cell1.innerHTML= tBoxCompany.value;
Cell2.innerHTML= tBoxAmount.value;
}
function addWorth()
{
var table1= document.getElementById("tableNetWorths");
var rowCount1= table1.rows.length;
var row1= table1.insertRow(rowCount1);
var arr= [];
for(count = 0; count < rowCount1; count++)
{
arr.push(table1.rows[count].cells[1].innerHTML);
}
arr.shift();
return arr;
}
function showWorthSum()
{
var returnedArr= [];
returnedArr.push(addWorth());
var totalWorth= 0;
var arrCount= 10 ;
for(int count = 0; count < arrCount; count++)
{
//totalWorth= totalWorth+ returnedArr[count];
document.write(returnedArr[count]);
//debugger;
}
//return totalWorth;
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<table id="tableNetWorths">
<tr>
<th>Company</th>
<th>Net Worth ($)</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>100</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>200</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>344</td>
</tr>
<tr>
<td>Island Trading</td>
<td>22</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>122</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>99</td>
</tr>
</table>
</div>
</div>
<div class="row">
<br>
<div class="col-md-3">
<input type="text" id="txtboxCompany" class="form-control"/>
</div>
<div class="col-md-3">
<input type="text" id="txtboxAmount" class="form-control"/>
</div>
<div class="col-md-3">
<button class="btn btn-primary" onclick="alterTable()" type="button">Add Rows</button>
</div>
<div class="col-md-3">
<button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>
</div>
</div>
</div>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>
Update: (ShowWorthSum function modified, still not working)
function showWorthSum()
{
var returnedArr= [];
returnedArr.push(addWorth());
var totalWorth= 0;
var arrCount= 10 ;
for(count = 0; count < arrCount; count++)
{
totalWorth= totalWorth+ returnedArr[count];
}
return totalWorth;
}
The problem is that you re not defining your variable count. Use this :
for(var count = 0; count < arrCount; count++){ ...
And with JS, no matter if your var is a string or an int, you allways declare your variable using var
remove 'int' from your for loop definition. You have:
for(int count = 0; count < arrCount; count++)
you need:
for(count = 0; count < arrCount; count++)
Also, your loop will return a series of 'undefined' results as it iterates past the number of elements in your actual array. You have six elements, you're looping a fixed 10 times. So once you get past the 6th element, all the rest return (correctly) as undefined.
Related
I need to make a little site that get some text boxes, ('Codigo' 'Nome' 'Documento') put on a array, that I already did, and make a a function with ForEach to create only one <tr> to three <td> I'm just not understand what I'm doing bad
function atualizarTabela() {
var tabelaBody = document.getElementById("corpo-tabela"); // corpo-tabela = tbody I need to clean it first
tabelaBody.innerHTML = "";
registros.forEach(function (registros) { // registros is my array that content the three text boxes
var createTr = document.createElement('tr');
for (var i = 0; i < registros[i]; i++) {
var createTd = document.createElement("td");
createTd.textContent = registro[i];
createTr.appendChild(createTd);
}
});
};
<body>
<table id="clientes">
<thead>
<tr>
<th>Codigo</th>
<th>Nome</th>
<th>Documento</th>
</tr>
</thead>
<tbody id="corpo-tabela">
</tbody>
</table>
<div id="bloco-dados">
<p>Código</p>
<input type="text" id="txtCodigo" name="Código">
<p>Nome</p>
<input type="text" id="txtNome" name="Nome">
<p>Documento</p>
<input type="text" id="txtDocumento" name="Documento"><br>
<input type="button" name="botao" id="btnSalvar" value="Salvar"><br>
<input type="button" name="botao2" id="btnNovo" value="Novo">
</div>
<script src="script.js" type="text/javascript"></script>
</body>
Thank you :)
Try removing the white space between function and the argument, and changing the argument to a dummy variable. So
registros.forEach(function(r) {
var createTr = document.createElement('tr');
for (var i = 0; i < r.length; i++) {
let createTd = document.createElement("td");
createTd.textContent = r[i];
createTr.appendChild(createTd);
tabelaBody.appendChild(createTr);
}
});
I am working on a phonebook. In html I have a div #containerAgenda which won't show if there are no added contacts. However, I created the function to delete a row or multiple rows. So if I add and then delete all contacts, I want the div to hide. I am not sure how to set the value to blank or empty so that I can apply the rule .classList.remove in the deleteRow function(I added the way I tried to define the input value as empty). Would you give me any hints? Below is my code:
P.S. I am quite a beginner so I appreciate non-complicated solutions :)
<script>
var persoane =[];
function deseneazaTabel(){
str = "";
for (var i = 0; i < persoane.length; i++){
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML=str;
}
var pers = {};
function adaugaContact(form,event){
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i=0; i<inputs.length; i++){
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow (idx){
persoane.splice(idx,1);
if(document.querySelectorAll("input[name]").value === ""){
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
</script>
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for ="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
What you need is if
(persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
inside deseneazaTabel function
I also added deleteAll functionality which was missing from your question please check demo
var persoane = [];
function deseneazaTabel() {
if (persoane.length === 0) {
document.getElementById('containerAgenda').style.display = 'none';
} else {
document.getElementById('containerAgenda').style.display = 'block';
}
str = "";
for (var i = 0; i < persoane.length; i++) {
str += `<tr>
<td>${persoane[i].name}</td>
<td>${persoane[i].telefon}</td>
<td><span class="editButton" onclick="editeaza();">EDIT</span></td>
<td><span class="deleteButton" onclick="deleteRow(${i});">STERGE</span></td>
</tr>`;
}
document.querySelector("table tbody").innerHTML = str;
}
function DeleteALL() {
persoane = [];
deseneazaTabel();
}
var pers = {};
function adaugaContact(form, event) {
event.preventDefault();
var inputs = form.querySelectorAll("input[name]");
for (var i = 0; i < inputs.length; i++) {
var a = inputs[i].getAttribute("name");
var v = inputs[i].value;
pers[a] = v;
}
persoane.push(pers);
document.querySelector("#containerAgenda").classList.remove("hidden");
deseneazaTabel();
}
function deleteRow(idx) {
persoane.splice(idx, 1);
if (document.querySelectorAll("input[name]").value === "") {
document.querySelector("#containerAgenda").classList.add("hidden");
}
deseneazaTabel();
}
<body onload="deseneazaTabel();">
<h1>AGENDA</h1>
<form class="orangeText centerText" onsubmit="adaugaContact(this,event);">
<label for="name">Nume</label>
<input type="text" name="name" id="name">
<label for="telefon">Telefon</label>
<input type="text" name="telefon" id="telefon">
<br/>
<input type="submit" class="btn" value="ADAUGA CONTACT">
</form>
<input type="submit" class="btn" onClick="DeleteALL()" value="Delete ALL">
<div id="containerAgenda" class="orangeText centerText hidden">
<table id="inputs">
<thead>
<tr>
<td>Nume</td>
<td>Telefon</td>
<td></td>
<td></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
This can help you
function checkIfNoContact() {
if(document.querySelectorAll("tr").length <= 0 ) {
document.querySelector("#containerAgenda").classList.add("hidden");
} else {
document.querySelector("#containerAgenda").classList.remove("hidden");
}
}
You can Use jQuery
It will check if there wasn't any <tr> in <tbody>, then hides div#containerAgenda
I hope it works for you.
if ( $("#containerAgenda tbody").children().length == 0 ) {
$("#containerAgenda").hide();
}
I made a table for the user input I've provided some textfield's so it can fill up the table. What I want to do I just want the user to fill up the table and let this save as pdf this will not create a records or insert in the database.
I just want totally save as pdf. But unfortunately when I <input type="text" class="form-control"> insert this in table data <td></td>. The value of the cell become this <input type="text" class="form-control">.
Table:
<div class = "col-md-12">
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class = "description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-success" id = "downloadPDF">Download as PDF</button>
</div>
Script:
function tableToJson(table)
{
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++)
{
headers[i] = table.rows[0].cells[i].innerHTML.replace();
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length; i++)
{
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++)
{
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function genPDF()
{
//tableToJson is a special function which converts HTML object to Javascript Object Notation
var table = tableToJson($('#customFields').get(0));
//Defining pdf object
var doc = new jsPDF('1','pt','letter',true);
doc.cellInitialize();
$.each(table, function(i, row)
{
$.each(row, function(j, cell)
{
if(j == "#description" | j == 0)
{
doc.cell(1,10,190,20,cell,i);
}
else
{
doc.cell(1,10,90,20,cell,i);
}
});
});
doc.save('text.pdf');
}
$(document).ready(function ()
{
$("#downloadPDF").click(function ()
{
javascript:genPDF();
});
});
Sample JFiddle:
$(document).ready(function() {
$("#addMore").click(function() {
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function() {
if ($('#customFields tbody tr').length == 1) {
} else {
$('#customFields tr:last').remove();
}
});
});
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.replace();
}
data.push(headers);
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function genPDF() {
//tableToJson is a special function which converts HTML object to Javascript Object Notation
var table = tableToJson($('#customFields').get(0));
//Defining pdf object
var doc = new jsPDF('1', 'pt', 'letter', true);
doc.cellInitialize();
$.each(table, function(i, row) {
$.each(row, function(j, cell) {
if (j == "#description" | j == 0) {
doc.cell(1, 10, 190, 20, cell, i);
} else {
doc.cell(1, 10, 90, 20, cell, i);
}
});
});
doc.save('text.pdf');
}
$(document).ready(function() {
$("#downloadPDF").click(function() {
javascript: genPDF();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12">
<table class="table" id="customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th class="description">Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary" id="addMore">+ Add</button>
<button type="submit" class="btn btn-danger" id="removeRow">- Remove</button>
<button type="submit" class="btn btn-success" id="downloadPDF">Download as PDF</button>
</div>
Cheers
Could loop through all the cells with <input> and replace those with their values before serializing the table to json
$('td:has(input)').text(function(){
return $(this).find('input').val();
});
I just decided to code a little html file which should create a multiplication table with integers from "start" to "end". Start and End are set before in a HTMl Form...
I can give 2 numbers as input and the tr and td elements are create but accessing them by ClassName and filling them with innerHTML does somehow not work.
Here is the Code:
<html>
<head>
<title>Das groࠥ 1x1</title>
<meta charset="utf-8">
</head>
<script type="text/javascript">
function malnehmen(Wert1, Wert2) {
Ausgabe = Wert1 * Wert2;
return Ausgabe;
}
function tabelle() {
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(i = start; i < end+1; i++) {
Reihe = document.createElement("tr");
att = document.createAttribute("class");
att.value = i + "a";
Reihe.setAttributeNode(att);
document.getElementById("Darein").appendChild(Reihe);
for(ii = start; ii < end+1; ii++) {
Feld = document.createElement("td");
att2 = document.createAttribute("class");
att2.value = malnehmen(i, ii);
Feld.setAttributeNode(att2);
Reihe.appendChild(Feld);
}
}
}
function ausfuellen() {
tabelle();
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(a = start; a < end+1; a++) {
alert("Hier denn?");
document.getElementsByClassName(a + "a").innerHTML = a.toString();
for(aa = start; aa < end+1; aa++) {
multi = malnehmen(a, aa);
alert("Angekommen");
document.getElementsByClassName(multi).innerHTML = multi.toString();
}
}
}
</script>
<body>
<FORM name="printer">
<TABLE>
<tr>
<td>Beginnt bei:</td>
<td>
<input type="number" name="anfang" size="3">
</td>
</tr>
<tr>
<td>Endet bei:</td>
<td>
<input type="number" name="ende" size="3">
</td>
</tr>
<tr>
<td>
<input type="button" name="wassolldas" value="Erstellen" onclick="javascript: tabelle();">
</td>
</tr>
</TABLE>
</FORM>
<br>
<TABLE id="Darein" border="1">
</TABLE>
</body>
Does anybody know what I did wrong?
I built in 2 alerts just to see if the javascript part reaches the for loop but there is no pop up in browser.
function toExcel(tableID)
{
var detailsTable = document.getElementById(tableID);
var oExcel = new ActiveXObject("Scripting.FileSystemObject");
var oBook = oExcel.Workbooks.Add;
var oSheet = oBook.Worksheets(1);
for (var y=0;y<detailsTable.rows.length;y++)
{
for (var x=0;x<detailsTable.rows(y).cells.length;x++)
{
oSheet.Cells(y+1,x+1) =detailsTable.rows(y).cells(x).innerText;
}
}
oExcel.Visible = true;
oExcel.UserControl = true;
}
As I posted here. However, can't test it myself. So let me know, if it works :)
<html>
<head>
<script type="text/javascript">
function CreateExcelSheet() {
var x = myTable.rows;
var xls = new ActiveXObject("Excel.Application");
xls.visible = true;
xls.Workbooks.Add;
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.Cells( i+1, j+1).Value = y[j].innerText;
}
}
}
</script>
</head>
<body>
<form>
<input type="button" onclick="CreateExcelSheet()" value="Create Excel Sheet">
</form>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
<td>Shivani</td>
<td>25</td>
</tr>
<tr>
<td>Naren </td>
<td>28</td>
</tr>
<tr>
<td>Logs</td>
<td>57</td>
</tr>
<tr>
<td>Kas</td>
<td>54</td>
</tr>
<tr>
<td>Sent</td>
<td>26</td>
</tr>
<tr>
<td>Bruce</td>
<td>7</td>
</tr>
</table>
</body>
</html>
<script language="javascript">
function runApp()
{
var Excel, Book;
var x=myTable.rows;
Excel = new ActiveXObject("Excel.Application");
Excel.Visible = true;
Book = Excel.Workbooks.Add();
for (i = 0; i < x.length; i++)
{
var y = x[i].cells;
for (j = 0; j < y.length; j++)
{
Book.ActiveSheet.Cells( i+1, j+1).Value = y[j].innerText;
}
}
}
</script>
And the HTML CODE
<table id="myTable">
....
</table>
<form>
<input type="button" onclick="runApp()" value="Export">
</form>
This should do the job.