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>
Related
I understood how to display the course of a crypto for example btc
image
The problem is that I would like to display the price of BTC and the price of ETH at the same time.
But, I don't know how to do it? I am stuck when I should add several cyptos... :S
I have my code here below:
const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
let stockPriceElement = document.getElementById('btcStockPrice');
let lastPrice = null;
ws.onmessage = (even) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceElement.innerText = price;
stockPriceElement.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
lastPrice = price;
}
I don't know how I should add ethcusdt#trade ?
Thank you for your help and your time.
const ws = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade');
let stockPriceElement = document.getElementById('btcStockPrice');
let lastPrice = null;
ws.onmessage = (even) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(2);
stockPriceElement.innerText = price;
stockPriceElement.style.color = !lastPrice || lastPrice === price ? 'black' : price > lastPrice ? 'green' : 'red';
lastPrice = price;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-3 pt-5">
<hr>
<table class="table table-bordered">
<thead class="table-success">
<tr class="text-center">
<th>BTC</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td><span id="btcStockPrice"></span></td>
</tr>
</tbody>
<thead class="table-success">
<tr class="text-center">
<th>ETH</th>
</tr>
</thead>
<tbody>
<tr class="text-center">
<td><span id="ethStockPrice"></span></td>
</tr>
</tbody>
</table>
<hr>
</div>
<script src="script.js"></script>
</body>
</html>
you can do it in different ways:
use the miniticker to get all info for all crypto and filter out to show only the ones you want :
'wss://stream.binance.com:9443/ws/!miniTicker#arr'
or use a combined stream for the data you want:
'wss://stream.binance.com:9443/stream?streams=btcusdt/ethusdt'
newbie here.. I was looking for some kind of function that can total the amount of one input type in table which is the Amount input.
I've tried parseInt function to the amount and its cell but it doesn't work.
I think its getting only the .innerHTML but not what it contains which should be the number.
var entryButton = document.getElementById('inputButton')
const tbodyEl = document.querySelector("tbody");
var row = 1;
//click button event
entryButton.addEventListener('click', tableDisplay);
//input value and displaying information
function tableDisplay(e) {
e.preventDefault()
var name = document.getElementById('inputName').value;
var amount = document.getElementById('inputAmount').value;
var date = document.getElementById('inputDate').value;
var remarks = document.getElementById('inputRemarks').value;
document.getElementById('inputName').value = '';
document.getElementById('inputAmount').value = '';
document.getElementById('inputDate').value = '';
document.getElementById('inputRemarks').value = '';
if (!name || !amount || !date || !remarks) {
alert("Please fill all the blanks")
return;
}
name.value = " ";
amount.value = " ";
date.value = " ";
remarks.value = " ";
var table = document.getElementById('displayTable');
var newRow = table.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = name
cell2.innerHTML = date
cell3.innerHTML = amount
cell4.innerHTML = remarks
selectedRow()
row++;
}
//adding total amount function??
<!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
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
<link
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css"
rel="stylesheet"
/>
<link
href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"
rel="stylesheet"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1 class="d-flex justify-content-center mb-5 mt-5">Expense Tracker</h1>
<form class="form d-flex justify-content-center mb-5">
<span class="fw-bolder m-1"
>Name: <input class="m-1" id="inputName" type="text"
/></span>
<span class="fw-bolder m-1"
>Date: <input class="m-1" id="inputDate" type="date"
/></span>
<span class="fw-bolder m-1"
>Amount: <input type="number" class="totalAmount m-1" id="inputAmount"
/></span>
<span class="fw-bolder m-1"
>Remarks <input class="m-1" id="inputRemarks" type="text"
/></span>
<button class="m-1" id="inputButton">
<i class="icon-level-down fs-4"></i>
</button>
<!-- How to delete specific row -->
<button class="m-1" type="button" id="deleteSelection">
<i class="icon-remove-sign fs-4"></i>
</button>
</form>
<table class="table m-5" id="displayTable">
<thead>
<tr id="numero">
<th scope="col">
<i class="icon-file-text fw-bolder fs-3"></i> Description
</th>
<th scope="col"><i class="icon-calendar fw-bolder fs-3"></i> Date</th>
<th scope="col"><i class="icon-usd fw-bolder fs-3"></i> Amount</th>
<th scope="col"><i class="icon-pencil fs-3"></i> Remarks</th>
</tr>
</thead>
<tbody></tbody>
</table>
<!-- //passing total amount?? -->
<span class="d-flex justify-content-center"
>Total: <input type="number" id="total" value="0" disabled
/></span>
<script src="script.js"></script>
</body>
</html>
I created a function called total(), which calculates the total of the column 'Amount' and prints it inside the input #total.
var entryButton = document.getElementById('inputButton')
const tbodyEl = document.querySelector("tbody");
var row = 1;
//click button event
entryButton.addEventListener('click', tableDisplay);
//input value and displaying information
function tableDisplay(e) {
e.preventDefault()
var name = document.getElementById('inputName').value;
var amount = document.getElementById('inputAmount').value;
var date = document.getElementById('inputDate').value;
var remarks = document.getElementById('inputRemarks').value;
document.getElementById('inputName').value = '';
document.getElementById('inputAmount').value = '';
document.getElementById('inputDate').value = '';
document.getElementById('inputRemarks').value = '';
if (!name || !amount || !date || !remarks) {
alert("Please fill all the blanks")
return;
}
name.value = " ";
amount.value = " ";
date.value = " ";
remarks.value = " ";
var table = document.getElementById('displayTable');
var newRow = table.insertRow(row);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
var cell4 = newRow.insertCell(3);
cell1.innerHTML = name
cell2.innerHTML = date
cell3.innerHTML = amount
cell4.innerHTML = remarks
total()
row++;
}
function total(){
var table = document.getElementById('displayTable');
let total = 0
for(let i = 1; i<table.rows.length; i++){
total+=Number(table.rows[i].cells[2].innerText)
}
const totalInput = document.getElementById('total')
totalInput.value=total
}
I am building a sample project named Tennis Club Management based on HTML,CSS,Javascript.In this i have html pages like profile.html, manageFees.html,index.js etc. In manageFees.html, when the page gets loaded, a dynamic table gets displayed which shows data from online API in tabular format and there is also a search box for searching the records.
Problem :- When i search a particular data(record) in search box. the search result gets displayed in the table , but the table heading gets disappeared and table CSS properties get distorted.
Below are the code files and Screenshots
index.js
/* --------------------MANAGE FEES PAGE------------------- */
/*----------TESTING CODE FOR SHOW FEES-----------*/
function showfees() {
console.log("Show Fees button clicked...");
document.querySelector(".showfees").style.display = "none";
document.querySelector("#feesregistration").style.display = "none";
if (istableCreated) {
document.querySelector("#table-responsive").style.display = "none";
}
document.querySelector(".searchbox").style.display = "block";
if (istableCreated == false) {
istableCreated = true;
var myTable = document.createElement("table");
myTable.className = "table-responsive";
myTable.id = "table-responsive";
myTable.style.marginLeft = "15%";
myTable.style.paddingLeft = "8%";
myTable.style.paddingRight = "11%";
document.body.appendChild(myTable);
var maintr = document.createElement("tr");
document.body.appendChild(myTable).appendChild(maintr);
var thmatchID = document.createElement("th");
thmatchID.innerHTML = "Match ID";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thmatchID);
var thmatchplayerName = document.createElement("th");
thmatchplayerName.innerHTML = "Player Name";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thmatchplayerName);
var thmatchDate = document.createElement("th");
thmatchDate.innerHTML = "Fees Date";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thmatchDate);
var thFeesAmount = document.createElement("th");
thFeesAmount.innerHTML = "Amount";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thFeesAmount);
var thMembershipType = document.createElement("th");
thMembershipType.innerHTML = "Membership Type";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thMembershipType);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
var JSONarr = JSON.parse(this.responseText);
console.log(JSONarr);
// ----------SUPER TESTING CODE-----------
for (var i = 0; i < JSONarr.length; i++) {
console.log(JSONarr[i].id, JSONarr[i].name, JSONarr[i].address.city, JSONarr[i].address.zipcode);
var myTr = document.createElement("tr");
document.body.appendChild(myTable).appendChild(myTr);
var tdID = document.createElement("td");
tdID.innerHTML = `${JSONarr[i].id}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdID);
var tdplayerName = document.createElement("td");
tdplayerName.innerHTML = `${JSONarr[i].name}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdplayerName);
var tdAddress = document.createElement("td");
tdAddress.innerHTML = `04/04/2020`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdAddress);
var tdFeesAmount = document.createElement("td");
tdFeesAmount.innerHTML = `10000`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdFeesAmount);
var tdMembershipType = document.createElement("td");
tdMembershipType.innerHTML = `Annually`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdMembershipType);
}
}
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users", true);
xhttp.send();
}
else {
document.querySelector("#table-responsive").style.display = "block";
}
if (statictableboolean == true) {
document.querySelector(".staticTable").style.display = "none";
}
// document.querySelector(".staticTable").style.display = "none";
}
//-------------SEARCHING IMPLEMENTATION IN SEARCH BOX----------------
function mySearch() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("searchbox");
filter = input.value.toUpperCase();
table = document.getElementById("table-responsive");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
}
else {
tr[i].style.display = "none";
}
}
}
manageFees.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Fees</title>
<!-- ADDING FONT AWESOME CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- ADDING BOOTSTRAP CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- ADDING STYLE.CSS -->
<link rel="stylesheet" href="/css/style.css">
</head>
<body onload="showfees()">
<!-- ADDING BUTTONS LIKE SHOW MATCHES, ADD MATCHES USING CSS BOOTSTRAP -->
<!-- <button type="button" class="btn btn-secondary showfees" onclick="showfees()">Show Fees</button> -->
<button type="button" class="btn btn-secondary addfees" onclick="addfees()">Add Fees</button>
<button type="button" class="btn btn-danger showfees" onclick="showfees()">Back</button>
<!-- ADDING SEARCH BAR -->
<input type="text" class="searchbox" id="searchbox" onkeyup="mySearch()" placeholder="Search by ID...">
<!-- CREATING REGISTRATION PAGE FOR ADDING FEES -->
<table class="feesregistration" id="feesregistration">
<!-- <tr>
<td>
<label>ID :</label>
</td>
<td>
<input type="text" class="feesid" id="feesid">
</td>
</tr> -->
<tr>
<td>
<label>Name :</label>
</td>
<td>
<input type="text" class="playerNameFees" id="playerNameFees" maxlength="40">
</td>
<td>
<label class="playerNameFeeserror"></label>
</td>
</tr>
<tr>
<td>
<label>Fees For :</label>
</td>
<td>
<select class="feesFor" id="feesFor">
<option value="select">---Select---</option>
<option value="court">Court</option>
<option value="tournament">Tournament</option>
<option value="both">Both</option>
</select>
</td>
<td>
<label class="feesForerror"></label>
</td>
</tr>
<tr>
<td>
<label>Fee Type :</label>
</td>
<td>
<select class="feesType" id="feesType">
<option value="select">---Select---</option>
<option value="monthly">Monthly</option>
<option value="halfyearly">Half Yearly</option>
<option value="annually">Annually</option>
</select>
</td>
<td>
<label class="feesTypeerror"></label>
</td>
</tr>
<tr>
<td>
<label>Date :</label>
</td>
<td>
<input type="date" class="feesdate">
</td>
<td>
<label class="feesdateerror"></label>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-success savefees" onclick="saveFees()">SAVE</button>
</td>
<td>
<button type="button" class="btn btn-info clearfees" onclick="clearfees()">CLEAR</button>
</td>
</tr>
</table>
<!-- ADDING BOOTSTRAP JS -->
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
<!-- ADDING INDEX.JS -->
<script src="/js/sidebar.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
Screenshots
Any solution please ?
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;
}
When I enter the value of the textbox has to be "" and the color has to be red. I have to use the same function for three textboxes. When I use document.getelementsbyclassname() my function won't work. Am I doing something wrong?
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<link rel="stylesheet" href="styleDOMoef01.css" type="text/css"/>
<title>DOMoef01</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript">
function roodVerdwijn(){
document.getElementsByClassName('text1').value="";
document.getElementsByClassName('text1').style.color = "Red";
document.getElementsByClassName('text1').style.background = "White";
}
function gedaan(){
document.getElementByClassName('text1').style.color = "Black";
document.getElementByClassName('text1').style.background = "Gray";
}
</script>
</head>
<body>
<table>
<tr>
<td colspan="2">persoonlijke gegevens</td>
</tr>
<tr>
<td>voornaam</td>
<td><input type="text" value="voornaam" class="text1" onfocus="roodVerdwijn();" onblur="gedaan();"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" value="achternaam" class="text1" onfocus="roodVerdwijn();" onblur="gedaan();"></td>
</tr>
<tr>
<td>adres</td>
<td><input type="text" value="adres" class="text1" onfocus="roodVerdwijn();" onblur="gedaan();"></td>
</tr>
<tr>
<td><input type="button" value="verzenden" onclick="window.alert('Bedankt om het formulier te verzenden')"></td>
<td><input type="button" value="alles wissen"></td>
</tr>
</table>
</body>
</html>
I've tried to fix it with this code but it still won't work:
function roodVerdwijn(){
var elements = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements.value="";
elements.style.color = "Red";
elements.style.background = "White";
}
}
function gedaan(){
var elements2 = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements2.style.color = "Black";
elements2.style.background = "Gray";
}
}
it kinda helped, but when I focus on one textbox, the value of all 3 textboxes are "". I want to focus on only one textbox. This is what i've changed:
function roodVerdwijn(){
var elements = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements[i].value="";
elements[i].style.color = "Red";
elements[i].style.background = "White";
}
}
function gedaan(){
var elements2 = document.getElementsByClassName('text1');
for(var i = 0 ; i<elements.length;i++){
elements2[i].style.color = "Black";
elements2[i].style.background = "Gray";
}
}
Get elements by class name returns an array of element. You have to loop each element or if you are sure that there's only one element for the class you have look for, use [0].
document.getElementsByClassName('text1')[0].value ...
I fixed it :
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<link rel="stylesheet" href="styleDOMoef01.css" type="text/css"/>
<title>DOMoef01</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript">
function roodVerdwijn(id){
var elements = document.getElementById(id);
elements.value="";
elements.style.color = "Red";
elements.style.background = "White";
}
function gedaan(id){
var elements2 = document.getElementById(id);
elements2.style.color = "Black";
elements2.style.background = "Gray";
}
</script>
</head>
<body>
<table>
<tr>
<td colspan="2">persoonlijke gegevens</td>
</tr>
<tr>
<td>voornaam</td>
<td><input type="text" value="voornaam" id="1" onfocus="roodVerdwijn(this.id);" onblur="gedaan(this.id);"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" value="achternaam" id="2" onfocus="roodVerdwijn(this.id);" onblur="gedaan(this.id);"></td>
</tr>
<tr>
<td>adres</td>
<td><input type="text" value="adres" id="3" onfocus="roodVerdwijn(this.id);" onblur="gedaan(this.id);"></td>
</tr>
<tr>
<td><input type="button" value="verzenden" onclick="window.alert('Bedankt om het formulier te verzenden')"></td>
<td><input type="button" value="alles wissen"></td>
</tr>
</table>
</body>
</html>