How to stop printing it again? (html, JavaScript) - javascript

This code is for printing a table and it's working fine but the problem is that when I click on print table button it prints the table but when I clicked it again it again prints the same table below I want it to not work again until the new input values are given. once it should print table and then don't until new values are given. I also want it to be more responsive.
<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<h2>MultiplicationTable</h2
<form action>
Table Number:<br>
<input type="text" id="TN" name="TableNumber">
<br>
Initial Number:<br>
<input type="text" id="IN" name="InitialNumber">
<br>
Ending Number:<br>
<input type="text" id="EN" name="EndingNumber">
</form>
<br><br>
<button id="again" onclick="myTable()">Print Table</button>
<br><br>
<button id="Bordertoggle" onclick="Bordertoggle()">Add Alternate Row Style</button>
<tr>
<button id="Hovertoggle" onclick="Hovertoggle()">Add Hover Effect</button>
<br><br>
<!-- <table class="table table-bordered table-striped table-hover" id="displayTables">
</table> -->
<table class="table" id="displayTables" border="0">
<tr></tr>
</table>
<!-- <table class="table table-bordered table-striped table-hover" id="HoverTables" border="1">
<tr></tr>
</table> -->
<!-- <p id="MT"></p> -->
<script>
// function myFunction()
// {
// var text = "";
// var Number = document.getElementById("TN").value;
// var T;
// var I = document.getElementById("IN").value;
// var E = document.getElementById("EN").value;
// for (T = I; T <= E; T++) {
// text += Number + "*" + T + "=" + Number*T + "<br>";
// }
// document.getElementById("MT").innerHTML = text;
// }
// function generateTable()
// {
// //var myVar = prompt("A number?", "");
// var myVar = document.forms.multTables.x.value;
// var myString = "<tr><th>"+ myVar + " times tables</th></tr>";
// for (i=1; i<=myVar; i++)
// {
// myString += "<tr><td>";
// myString += i+ " x " +myVar+ " = " +(i*myVar)+ "\n";
// myString += "</td></tr>";
// }
// document.getElementById('t').innerHTML = myString;
// return false;
// }
function myTable()
{
var Number = document.getElementById("TN").value;
var T;
var I = document.getElementById("IN").value;
var E = document.getElementById("EN").value;
var temp="";
for (T = I; T <= E; T++) {
temp+="<tr><td>"+Number+"</td><td>*</td><td>" + T + "</td><td>=</td><td>" + Number*T +"</td></tr>";
}
$("#displayTables").append(temp);
}
function Bordertoggle() {
var element = document.getElementById("displayTables");
element.classList.toggle("table-bordered");
var change = document.getElementById("Bordertoggle");
if (change.innerHTML == "Add Alternate Row Style")
{
change.innerHTML = "Remove Alternate Row Style";
}
else {
change.innerHTML = "Add Alternate Row Style";
}
}
function Hovertoggle() {
var element = document.getElementById("displayTables");
element.classList.toggle("table-hover");
var change = document.getElementById("Hovertoggle");
if (change.innerHTML == "Add Hover Effect")
{
change.innerHTML = "Remove Hover Effect";
}
else {
change.innerHTML = "Add Hover Effect";
}
}
</script>
</body>
</html>

Just save the current value in variable and when next time user clicks check if value matches then don't print otherwise print.
var prevN, prevI, prevE; //store value in this variable of previous state
function myTable() {
var Number = document.getElementById("TN").value;
var T;
var I = document.getElementById("IN").value;
var E = document.getElementById("EN").value;
var temp = "";
if (prevN !== Number || prevE !== E || prevI !== I) { //here check if value is changed or not
prevN = Number;
prevE = E;
prevI = I;
for (T = I; T <= E; T++) {
temp += "<tr><td>" + Number + "</td><td>*</td><td>" + T + "</td><td>=</td><td>" + Number * T + "</td></tr>";
}
$("#displayTables").append(temp);
}
}
function Bordertoggle() {
var element = document.getElementById("displayTables");
element.classList.toggle("table-bordered");
var change = document.getElementById("Bordertoggle");
if (change.innerHTML == "Add Alternate Row Style") {
change.innerHTML = "Remove Alternate Row Style";
} else {
change.innerHTML = "Add Alternate Row Style";
}
}
function Hovertoggle() {
var element = document.getElementById("displayTables");
element.classList.toggle("table-hover");
var change = document.getElementById("Hovertoggle");
if (change.innerHTML == "Add Hover Effect") {
change.innerHTML = "Remove Hover Effect";
} else {
change.innerHTML = "Add Hover Effect";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<h2>MultiplicationTable</h2 <form action>
Table Number:<br>
<input type="text" id="TN" name="TableNumber">
<br> Initial Number:<br>
<input type="text" id="IN" name="InitialNumber">
<br> Ending Number:<br>
<input type="text" id="EN" name="EndingNumber">
</form>
<br><br>
<button id="again" onclick="myTable()">Print Table</button>
<br><br>
<button id="Bordertoggle" onclick="Bordertoggle()">Add Alternate Row Style</button>
<tr>
<button id="Hovertoggle" onclick="Hovertoggle()">Add Hover Effect</button>
<br><br>
<!-- <table class="table table-bordered table-striped table-hover" id="displayTables">
</table> -->
<table class="table" id="displayTables" border="0">
<tr></tr>
</table>
<!-- <table class="table table-bordered table-striped table-hover" id="HoverTables" border="1">
<tr></tr>
</table> -->
<!-- <p id="MT"></p> -->
</body>
</html>

add a var to your ajavascript, like
printed = 0;
once you print your table, do
printed = 1;
Print only
if ( printed == 0 )
....print
?
Edit:
printed=0;
......
if(printed==0) {
$("#displayTables").append(temp);
printed=1;
}

Related

JavaScript Expense Tracker Calculator - Subtraction

Im trying to do a expense tracker with vanilla javascript that user can can add/remove their expense item and the Total of expense will be calculated accordingly.
I am using constructor to create object so later I can save in localStorage later and retrieve later (hv not done this part yet)
Here is the problem. There is no problem in adding atm but when it comes to removing item (if not remove in sequence), the calculation is messed up. E.g. Item 1, Item 2, Item 3. If I remove with order Item 3 --> Item2 --> Item No problem with total value of subtraction. But if start the removal from Item 1 or Item 2, the calculation will be messed up
Im not sure is it because there is no index/id in each item so calculation is not working. Appreciate for any help thank you!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="ExpenseTracker.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<label name="expense">Expense: </label>
<input id="inputField" name="expense" type="text">
<label name="date">Date: </label>
<input id="start" type="text" name="date">
<label name="amount">Amount: </label>
<input id="money" name="amount" type="number" min="0" step="0.1">
<button id="add" >Add</button>
<table>
<thead>
<tr style="border: 1px solid black;">
<th>Description</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="listContainer" style="border: 1px solid black;">
</tbody>
<tr>
<td id="total">total</td>
</tr>
</table>
<button onclick="clearHistory()">clear localStorage</button>
</div>
<script>
class ExpenseObject{
constructor(e, d, a){
this.expenseDescription = e;
this.dateObject = d;
this.amount = a;
}
}
function clearHistory(){
localStorage.clear();
}
const createDate = flatpickr("#start",{
dateFormat:"d-m-Y ",
});
let addButton = document.getElementById("add");
let listContainer=document.getElementById("listContainer");
let inputField= document.getElementById("inputField");
let dateInput = document.getElementById("start");
let amountField = document.getElementById("money");
let total = document.getElementById("total");
addButton.addEventListener('click', function(){
if(!inputField.value || !dateInput.value || !amountField.value){
alert("please do not leave blank in any field");
return;
}
var newRow = document.createElement('tr');
var expense = document.createElement('td');
var expenseDate = document.createElement('td');
var expenseAmount = document.createElement('td');
var deleteButton = document.createElement('button');
deleteButton.innerHTML="X";
let expenseStuff = new ExpenseObject (inputField.value,dateInput.value,amountField.value )
expense.innerHTML = expenseStuff.expenseDescription;
expenseDate.innerHTML = expenseStuff.dateObject;
expenseAmount.innerText = expenseStuff.amount;
listContainer.appendChild(newRow);
newRow.appendChild(expense);
newRow.appendChild(expenseDate);
newRow.appendChild(expenseAmount);
newRow.appendChild(deleteButton);
inputField.value = "";
amountField.value="";
var totalAmount = parseFloat(total.innerText) || 0;
totalAmount += parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
deleteButton.addEventListener('click', function(){
newRow.removeChild(expense);
newRow.removeChild(expenseDate);
newRow.removeChild(expenseAmount);
newRow.removeChild(deleteButton);
totalAmount -= parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
})
})
</script>
</body>
</html>
The primary issue you were experiencing is that you declared totalAmount at the local scope, so each deleteButton event listner still references the old totalAmount value from when the listener was declared. If you declare that value in a higher-level scope, alongside total, everything works as expected.
Here it is in action:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="ExpenseTracker.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<label name="expense">Expense: </label>
<input id="inputField" name="expense" type="text">
<label name="date">Date: </label>
<input id="start" type="text" name="date">
<label name="amount">Amount: </label>
<input id="money" name="amount" type="number" min="0" step="0.1">
<button id="add" >Add</button>
<table>
<thead>
<tr style="border: 1px solid black;">
<th>Description</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody id="listContainer" style="border: 1px solid black;">
</tbody>
<tr>
<td id="total">total</td>
</tr>
</table>
<button onclick="clearHistory()">clear localStorage</button>
</div>
<script>
class ExpenseObject{
constructor(e, d, a){
this.expenseDescription = e;
this.dateObject = d;
this.amount = a;
}
}
function clearHistory(){
localStorage.clear();
}
const createDate = flatpickr("#start",{
dateFormat:"d-m-Y ",
});
let addButton = document.getElementById("add");
let listContainer = document.getElementById("listContainer");
let inputField = document.getElementById("inputField");
let dateInput = document.getElementById("start");
let amountField = document.getElementById("money");
let total = document.getElementById("total");
let totalAmount = parseFloat(total.innerText) || 0;
addButton.addEventListener('click', function(){
if(!inputField.value || !dateInput.value || !amountField.value){
alert("please do not leave blank in any field");
return;
}
const newRow = document.createElement('tr');
const expense = document.createElement('td');
const expenseDate = document.createElement('td');
const expenseAmount = document.createElement('td');
const deleteButton = document.createElement('button');
deleteButton.innerHTML="X";
let expenseStuff = new ExpenseObject (inputField.value,dateInput.value,amountField.value )
expense.innerHTML = expenseStuff.expenseDescription;
expenseDate.innerHTML = expenseStuff.dateObject;
expenseAmount.innerText = expenseStuff.amount;
listContainer.appendChild(newRow);
newRow.appendChild(expense);
newRow.appendChild(expenseDate);
newRow.appendChild(expenseAmount);
newRow.appendChild(deleteButton);
inputField.value = "";
amountField.value = "";
totalAmount += parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
deleteButton.addEventListener('click', function() {
newRow.removeChild(expense);
newRow.removeChild(expenseDate);
newRow.removeChild(expenseAmount);
newRow.removeChild(deleteButton);
totalAmount -= parseFloat(expenseAmount.innerHTML);
total.innerHTML = totalAmount;
})
})
</script>
</body>
</html>

Create a searchable telephone directory with Google Sheets and Apps Script?

I work for a charity who are google cloud based. They have limited resources and no SQL database, I have been asked to develop a searchable telephone directory that sits on our intranet.
Please see the code.gs below:
function doGet(e){
var ss = SpreadsheetApp.openById('sheetId');
var sheet = ss.getSheetByName('Staff');
var range = sheet.getDataRange();
var values = range.getValues();
var holderArray = [];
var HTMLTemp = HtmlService.createTemplateFromFile('index');
Logger.log(values);
var holder = '';
for(x=1; x<values.length; x++){
holderArray.push({
"firstname" : values[x][0],
"lastname" : values[x][1],
"service" : values[x][2],
"role" : values[x][3],
"location" : values[x][4],
"deskphone" : values[x][5],
"mobilephone" : values[x][6],
"email" : values[x][7]
});
}
HTMLTemp.data = holderArray;
var html = HTMLTemp.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function myFunction1(){
var ss = SpreadsheetApp.openById('sheetid');
var sheet = ss.getSheetByName('Staff');
var range = sheet.getDataRange();
var values = range.getValues();
var holderArray = [];
var HTMLTemp = HtmlService.createTemplateFromFile('index');
Logger.log(values);
var holder = '';
for(x=1; x<values.length; x++){
holderArray.push({
"firstname" : values[x][0],
"lastname" : values[x][1],
"service" : values[x][2],
"role" : values[x][3],
"location" : values[x][4],
"deskphone" : values[x][5],
"mobilephone" : values[x][6],
"email" : values[x][7]
});
}
HTMLTemp.data = holderArray;
var html = HTMLTemp.evaluate().setWidth(1020).setHeight(800);
SpreadsheetApp.getUi().showModalDialog(html, 'Title');
I will be deploying this as a web app, and have included the index.html below too:
<script>
var datags = <?!= JSON.stringify(data) ?>;
</script>
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous">
</head>
<body>
<div style="padding: 5px 20px; width: 50%;">
<header class="text-center" style="padding: 15px;">
<h1>Age UK Essex Staff Directory</h1>
</header>
<input type="text" id="filter"/>
<input type="button" id="btnFilter" value="Filter" />
<table id="myTable" class="table table-striped" style="margin-top: 10px;">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Service</th>
<th>Role</th>
<th>Location</th>
<th>Desk Phone</th>
<th>Mobile Phone</th>
<th>Email</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function(){
console.log(datags);
jQuery.each(datags, function() {
console.log(this);
$('#myTable tr:last').after('<tr style="font-size: 12px; font-family: arial;"><td>'+this.firstname+'</td><td>'+this.lastname+'</td><td>'+this.service+'</td><td>'+this.role+'</td><td>'+this.location+'</td><td>'+this.deskphone+'</td><td>'+this.mobilephone+'</td><td>'+this.email+'</td></tr>')
})
});
</script>
<script>
$(document).ready(function() {
$("#btnFilter").click(function() {
$("#myTable tr").show();
if($("#filter").val.length > 0) {
$("#myTable tr").filter(function(index, elm) {
return $(elm).html().toUpperCase().indexOf($("#filter").val().toUpperCase()) < 0;
}).hide();
}
});
});
</script>
</body>
</html>
This works for the most part although when I remove the seacrh criteria I'd prefer it if the content returned to normal rather than staying on the results of the previous seatch.
You can use setInterval to run the filter function, every X milliseconds.
Modify your HTML to the following for example:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div style="padding: 5px 20px; width: 50%;">
<header class="text-center" style="padding: 15px;">
<h1>Age UK Essex Staff Directory</h1>
</header>
<input type="text" placeholder="Filter directory..." id="filter" />
<input type="button" id="btnFilter" value="Filter" />
<table id="myTable" class="table table-striped" style="margin-top: 10px;">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Service</th>
<th>Role</th>
<th>Location</th>
<th>Desk Phone</th>
<th>Mobile Phone</th>
<th>Email</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var datags = <?!= JSON.stringify(data) ?> ;
console.log(datags);
function initialize() {
jQuery.each(datags, function() {
$('#myTable tr:last').after('<tr style="font-size: 12px; font-family: arial;"><td>'
+ this.firstname + '</td><td>'
+ this.lastname + '</td><td>'
+ this.service + '</td><td>'
+ this.role + '</td><td>'
+ this.location + '</td><td>'
+ this.deskphone + '</td><td>'
+ this.mobilephone + '</td><td>'
+ this.email + '</td></tr>'
)
});
}
function filter() {
$("#myTable tr").show();
if ($("#filter").val.length > 0) {
$("#myTable tr").filter(function(index, elm) {
return $(elm).html().toUpperCase().indexOf($("#filter").val().toUpperCase()) < 0;
}).hide();
}
}
$(document).ready(
function() {
initialize();
$("#btnFilter").click(filter);
setInterval(filter, 1000);
}
);
</script>
</body>
</html>
References:
JS built in function setInterval
You can create a filter on your table:
Just mark the area where your data is and go to "Data" -> "Filter"
But I don't know if there's a better solution with google cloud.

Javascript writing into Table not working

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.

If/Then statements with checkboxes (html)

I'm trying to create a Javascript if/then statement that goes along the lines of: if all of the checkboxes are checked then show this image, else show this other image. I'm completly stuck and not sure what to do...
<head>
<center>
<FONT FACE="LYDIAN,COMIC SANS MS,ARIAL" COLOR="#BDF6F4" SIZE="6"><MARQUEE LOOP="N"|"INFINITE" BGCOLOR="#E0BDF6" WIDTH="68%" HEIGHT="60" ALIGN="MIDDLE" HSPACE="4%" VSPACE="25">My To-Do List: Just Do It!</MARQUEE></FONT>
<p>
<span style="color:#937AF0">
Put 'To-Do' tasks in order according to priority, to add a new task simply click the add button. When task on list is completed, check done!
</p>
</center>
<style>
table, th, td
{
border: 1px solid black;
}
</style>
</head>
<body>
<body style="background:#E6E6FA">
<center>
<table id="specialtable">
<table style="background:#BDF6F4">
<tr>
<th> Done</th>
<th>Priority</th>
<th>Task</th>
</tr>
<tr>
<td><input type="checkbox"</td>
<td>1<br></td>
<td><input type="text"></td>
<td><button onclick="addRow(this);">Add</button><br></td>
</tr>
</table>
</center>
<script type = "text/javascript">
function addRow(e)
{
var current = e.parentNode.parentNode; // <tr>...</tr>
var tnew = current.cloneNode(true);
var rowCount = current.parentNode.getElementsByTagName("tr").length;
tnew.getElementsByTagName("td")[1].textContent = rowCount;
current.parentNode.appendChild(tnew);
}
</script>
</head>
<body>
You could code:
var thisImage = document.getElementById('thisImage'),
thatImage = document.getElementById('thatImage'),
checkboxes = document.querySelectorAll('input[type=checkbox]'),
cLen = checkboxes.length;
function changeHandler() {
// compare the length of the checkboxes
// with the length of checked ones
var allChecked = Array.prototype.filter.call(checkboxes, function(e) {
return e.checked;
}).length === cLen;
if (allChecked) {
thisImage.style.display = 'block';
thatImage.style.display = 'none';
} else {
thisImage.style.display = 'none';
thatImage.style.display = 'block';
}
}
Array.prototype.forEach.call(checkboxes, function (e) {
e.addEventListener('change', changeHandler, false);
});
Refer this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function count(obj){
var x = document.getElementsByTagName("INPUT");
var y = [];
for (var cnt = 0; cnt < x.length; cnt++) {
if (x[cnt].type == "checkbox") y.push(x[cnt]);
}
var chkboxCount = y.length;
var cnt = 0;
for(var i=1; i<=chkboxCount; i++){
var checkbox = 'chk' + i;
if(document.getElementById(checkbox).checked){
cnt++;
}
}
if(cnt == 3){
document.getElementById('pic').innerHTML = '<img src = "img_flwr.gif">';
} else{
document.getElementById('pic').innerHTML = '<img src = "img_tree.gif">';
}
}
</script>
<input type="checkbox" name="chk1" id="chk1" onclick="count(this)">
<input type="checkbox" name="chk2" id="chk2" onclick="count(this)">
<input type="checkbox" name="chk3" id="chk3" onclick="count(this)">
<br>
<div id="pic"></div>
</body>
</html>

How to send an HTML table,which is created dynamically using javascript,to a another page(servlet,jsp etc)?

How to send an HTML table, which is created dynamically using javascript, to a another page (servlet,jsp etc)?
My Code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript">
function createTable(numberOfRows) {
for ( var i = 1; i < numberOfRows; i++) {
var tr = document.createElement("tr");
var tableData = ['hello','world','hi','bye'];
for ( var j = 0; j < tableData.length; j++) {
var td = document.createElement("td");
var data = document.createTextNode(tableData[j]);
td.appendChild(data);
tr.appendChild(td);
}
document.getElementById("table1").appendChild(tr);
}
}
function sendTableToAnotherPage(){
// **what should be the code here,to fetch the table created using above function
//and send it to servlet or jsp page via AJAX.**
}
</script>
</head>
<body>
<table id="table1">
</table>
<button type="button" onclick="createTable(5)">Create Table</button>
<input type="button" value="Save" onclick="sendTableToAnotherPage()">
</body>
</html>
I am facing difficulty in fetching the table data from my servlet/jsp page.
Any help, would be highly appreciated.
If table and data is same then, you can pass table.innerHTML to another page.
example:
<script type="text/javascript">
function createTable(numberOfRows) {
for ( var i = 1; i < numberOfRows; i++) {
var tr = document.createElement("tr");
var tableData = ['hello','world','hi','bye'];
for ( var j = 0; j < tableData.length; j++) {
var td = document.createElement("td");
var data = document.createTextNode(tableData[j]);
td.appendChild(data);
tr.appendChild(td);
}
document.getElementById("table1").appendChild(tr);
}
}
function sendTableToAnotherPage(){
document.getElementById("table2").innerHTML = document.getElementById("table1").innerHTML;
}
</script>
<table id="table2" border="2">
</table>
<table id="table1">
</table>
<button type="button" onclick="createTable(5)">Create Table</button>
<input type="button" value="Save" onclick="sendTableToAnotherPage()">

Categories