how to apply discount - javascript

I am building a ticket purchase system to get better in my javascript. I need help with some of my code. I can get the total of everything I want, but I am unable to get my discount function to work.
The total is calculated as (Show price * number of tickets) + (price of the delivery method)
when: the number of tickets > 6 the discount should be 10 per cent of the total.
when: the number of tickets > 10 the discount should be 15 per cent of the total.
the discount should be displayed separately to the total.
Dont mind some of the code that are comments as i used that as refrences.
This is the code:
java script:
//constants
const name = document.getElementById("fname");
const noofaddress = document.getElementById("noofaddress");
const shows = document.getElementById("shows");
const delivery = document.getElementById("delivery");
const displaytotal = document.getElementById("displaytotal");
const seatprice = document.getElementById("seatprice");
const order = document.getElementById("book");
const showselect = document.querySelector("#shows");
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//amount
var showprices = new Array();
showprices["79"]=79;
showprices["85"]=85;
showprices["67"]=67;
showprices["83"]=83;
function getshowprice() {
const display = document.getElementById("display");
var showprice = 0;
var form = document.forms["bookform"];
var selectedshow = form.elements["shows"]
showprice = showprices[selectedshow.value];
return showprice;
}
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//functions
//function calculateshowcost() {
//showcost = Number(this.value);
//document.getElementById('display').innerHTML = (`£${bookform.shows[bookform.shows.selectedIndex].value}`);
//}
//delivery funtion
//function getDeliveryValue() {
// document.getElementById('displaydelivery').innerHTML = (`£${bookform.delivery[bookform.delivery.selectedIndex].value}`);
//}
var deliveryprices = new Array();
deliveryprices["0"]=0;
deliveryprices["1.50"]=1.50;
deliveryprices["3.99"]=3.99;
function getdeliveryprice() {
const displaydelivery = document.getElementById("displaydelivery");
var deliveryprice = 0;
var form = document.forms["bookform"];
var selecteddelivery = form.elements["delivery"]
deliveryprice = deliveryprices[selecteddelivery.value];
return deliveryprice;
}
function gettotal() {
const displaytotal = document.getElementById("displaytotal");
const seats = document.getElementById("seats");
const noofseats = document.querySelector("#seats");
var showtotal = getshowprice()
var showdeliverytotal = getdeliveryprice()
var seatstotal = noofseats.value;
displaytotal.innerText = (`Total: £${(showtotal * seatstotal) + (showdeliverytotal)}`);
}
function getdiscount(products, showtotal, seatstotal) {
const discount = document.getElementById('discount');
var x = 6
if (seatstotal > x) {
(seatstotal > 10)
DiscountPrice = showtotal - (showtotal * .10)
}
else if
{
DiscountPrice = showtotal - (showtotal * .10)
}
return showtotal > y;
discount.innerText = (`discount: £${(DiscountPrice)}`);
// total
//function totalprice(event) {
//event.preventDefault()
//showprice = Number(showselect.value);
//totalnumberoftickets = Number(noofseats.value);
//totalcost = (showprice * totalnumberoftickets) + deliverycost;
//displaytotal.innerText = totalTickets;
//totalPriceResult.innerText = totalPrice;
//console.log("thank you for your order")
//}
html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="theatre tickets page for assignment">
<link rel="stylesheet" href="theatretickets.css">
<title>Theatre Tickets</title>
</head>
<body class="background">
<script src="theatretickets.js"></script>
<img class="logoimage" src="" alt="logo">
<h1 class="title">Theatre Tickets</h1>
<!--navigation -->
<nav>
<ul class="a">
<li class="hp">Fruit Machine</li>
<li class="hp">Theatre Tickets</li>
</ul><br><br>
</nav>
<!--forms-->
<!--name-->
<form name="bookform" id="bookform" class="fullform" method="post">
<h2>Name</h2>
<label for="fname">Full Name</label><br>
<input type="text" id="fname" name="fname" required=""><br>
<!--address-->
<h2>Address</h2>
<label for="noofaddress">Full Address</label><br>
<input type="text" id="noofaddress" name="noofaddress" required=""><br>
<!--shows-->
<h2>Currently Available Shows</h2>
<select name="shows" id="shows" onchange="getshowprice()">
<option value="79" selected class="Phantom" id="Phantom">Phantom Of The Opera</option>
<option value="85" class="hamilton" id="hamilton">Hamilton</option>
<option value="67" class="lionking" id="lionking">Lion King</option>
<option value="83" class="misssaigon" id="misssaigon">Miss Saigon</option>
</select><br>
<label id="display"></label>
<!--delivery-->
<h2>Method Of Delivery</h2>
<select id="delivery" name="delivery" onchange="getdeliveryprice()">
<option id="eticket" value="0" selected>E-Ticket</option>
<option id="boxoffice" value="1.50">Collect from Box Office</option>
<option id="posted" value="3.99">Posted</option>
</select><br>
<!--display the delivery cost label-->
<label id="displaydelivery"></label>
<!--seats-->
<h2>Number Of Seats</h2>
<input type="number" id="seats" name="seats" min="1" required=""
placeholder="Number of Seats"><br>
<label id="seatprice"></label><br><br>
<!--book button-->
<button type="button" name="book" id="book" onclick="gettotal()">Book</button><br><br>
<div id= "displaytotal"></div>
<div id="discount"></div>
<div id="finalcost"></div>
</form>
</body>

When no. of ticket is greater than 10, you are still applying 10%, so replace it with 15%, and I think you should first check condition for 10 and then condition for 6 in your if-else, see the new edited code. I don't know what is y here so can't comment on that.
//constants
const name = document.getElementById("fname");
const noofaddress = document.getElementById("noofaddress");
const shows = document.getElementById("shows");
const delivery = document.getElementById("delivery");
const displaytotal = document.getElementById("displaytotal");
const seatprice = document.getElementById("seatprice");
const order = document.getElementById("book");
const showselect = document.querySelector("#shows");
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//amount
var showprices = new Array();
showprices["79"]=79;
showprices["85"]=85;
showprices["67"]=67;
showprices["83"]=83;
function getshowprice() {
const display = document.getElementById("display");
var showprice = 0;
var form = document.forms["bookform"];
var selectedshow = form.elements["shows"]
showprice = showprices[selectedshow.value];
return showprice;
}
//event listeners
//order.addEventListener("click", gettotal);
//showselect.addEventListener("change", getshowprice);
//functions
//function calculateshowcost() {
//showcost = Number(this.value);
//document.getElementById('display').innerHTML = (`£${bookform.shows[bookform.shows.selectedIndex].value}`);
//}
//delivery funtion
//function getDeliveryValue() {
// document.getElementById('displaydelivery').innerHTML = (`£${bookform.delivery[bookform.delivery.selectedIndex].value}`);
//}
var deliveryprices = new Array();
deliveryprices["0"]=0;
deliveryprices["1.50"]=1.50;
deliveryprices["3.99"]=3.99;
function getdeliveryprice() {
const displaydelivery = document.getElementById("displaydelivery");
var deliveryprice = 0;
var form = document.forms["bookform"];
var selecteddelivery = form.elements["delivery"]
deliveryprice = deliveryprices[selecteddelivery.value];
return deliveryprice;
}
function gettotal() {
const displaytotal = document.getElementById("displaytotal");
const seats = document.getElementById("seats");
const noofseats = document.querySelector("#seats");
var showtotal = getshowprice()
var showdeliverytotal = getdeliveryprice()
var seatstotal = noofseats.value;
displaytotal.innerText = (`Total: £${(showtotal * seatstotal) + (showdeliverytotal)}`);
}
function getdiscount(products, showtotal, seatstotal) {
const discount = document.getElementById('discount');
var x = 10;
var DiscountPrice = 0;
if (seatstotal > x) {
DiscountPrice = showtotal - (showtotal * .15)
}
else if
(seatstotal > 6)
DiscountPrice = showtotal - (showtotal * .10)
}
return showtotal > y;
discount.innerText = (`discount: £${(DiscountPrice)}`);
// total
//function totalprice(event) {
//event.preventDefault()
//showprice = Number(showselect.value);
//totalnumberoftickets = Number(noofseats.value);
//totalcost = (showprice * totalnumberoftickets) + deliverycost;
//displaytotal.innerText = totalTickets;
//totalPriceResult.innerText = totalPrice;
//console.log("thank you for your order")
//}

Related

How to implement a function that obtains the percentage corresponding to each counter?

The percentage will be updated depending on the two counters. I have to have as total data the sum of counter and counter1
var botonElement = document.getElementById("botonClick");
var pElement = document.getElementById("areaContador");
var pPorce = document.getElementById("porcen");
var contador = 0;
var botonElement1 = document.getElementById("botonClick1");
var pElement1 = document.getElementById("areaContador1");
var pPorce1 = document.getElementById("porcen1");
var contador1 = 0;
botonElement.onclick = function () {
contador++;
pElement.textContent = contador;
/* pPorce.textContent = result + "%"; */
}
botonElement1.onclick = function () {
contador1++;
pElement1.textContent = contador1;
/* pPorce1.textContent = result + "%"; */
}
Looks like you are looking for something like below.
function increaseCounter(index) {
const countElement1 = document.getElementById("counter1");
const countElement2 = document.getElementById("counter2");
const currentCountElement = document.getElementById("counter" + index);
currentCountElement.value = parseInt(currentCountElement.value) + 1;
const value1 = parseInt(countElement1.value);
const value2 = parseInt(countElement2.value);
const total = value1 + value2;
const perc1 = ((value1/total) * 100).toFixed(2);
const perc2 = ((value2/total) * 100).toFixed(2);
document.getElementById("percentage1").innerHTML = perc1;
document.getElementById("percentage2").innerHTML = perc2;
}
.container {
display: flex;
background-color: #993355;
color: #ffffff;
}
<div class="container">
<div>
<h3>Area 1</h3>
<div>Count: <input type="text" value="0" id="counter1" /></div>
<div>Percentage: <label id="percentage1"></label></div>
<div><button onclick="increaseCounter(1)">Click Here!</button></div>
</div>
<div>
<h3>Area 2</h3>
<div>Count: <input type="text" value="0" id="counter2" /></div>
<div>Percentage: <label id="percentage2"></label></div>
<div><button onclick="increaseCounter(2)">Click Here!</button></div>
</div>
</div>

Cannot set innerHTML on one, of two, identical functions

I have two functions that are essentially identical. The negIndex function works as advertised, no problems, but the posIndex function give me the error "cannot set enterTable.innerHTML to 'null'".
I'm fairly new to Javascript so it could be something obvious, but if it is i'm lost. I've tried a few different things without positive results. Any help would be appreciated.
The HTML
<ul id="exitTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: center"></ul>
<br>
<ul id="enterTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: center"></ul>
The Javascript
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const price = document.querySelector('#stockPrice');
const shares = document.querySelector('#sharesAmount');
const commission = document.querySelector('#commissionAmount');
const fee = document.querySelector('#feeAmount');
const max = document.querySelector('#maxGain');
const msg = document.querySelector('.msg');
const exitTable = document.querySelector('#exitTable');
const enterTable = document.querySelector('#enterTable');
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if (price.value === '' || shares.value === '') {
// alert
msg.classList.add('error');
msg.innerHTML = 'Please enter required fields';
// Remove error after 3 seconds
setTimeout(() => msg.remove(), 3000);
} else {
let subTotal = price.value * shares.value;
subTotal = subTotal.toFixed(2)
let total = subTotal + parseFloat(commission.value);
function popList(name) {
let li = document.createElement('li');
li.textContent = name;
li.style.cssText = 'text-align: center'
return li;
}
//finds the 5%-50% loss amounts based on subTotal
function negIndex(num) {
let negPer = -0.05;
let negArray = [];
let i = 0;
exitTable.innerHTML = "";
while (negPer >= -0.50) {
negArray[i] = parseFloat(num * negPer).toFixed(2);
let s = parseFloat(negPer * 100).toFixed(1) + "% " + negArray[i];
let x = popList(s); //creating list elements
exitTable.appendChild(x);
i++;
negPer += -0.05;
}
}
function posIndex(num) {
let posPer = 0.05;
let posArray = [];
let i = 0;
enterTable.innerHTML = "";
while (posPer <= 1.00) {
posArray[i] = parseFloat(num * posPer).toFixed(2);
let s = parseFloat(posPer * 100).toFixed(1) + "% ->" + posArray[i];
let x = popList(s);
enterTable.appendChild(x);
i++;
posPer += 0.05;
}
}
posIndex(subTotal);
negIndex(subTotal);
}
//Listen for form clear
myForm.addEventListener('reset', onReset);
function onReset() {
price.innerHTML = "";
shares.innerHTML = "";
commission.innerHTML = "";
fee.innerHTML = "";
}
I'm just gessing what your html could look like
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const price = document.querySelector('#stockPrice');
const shares = document.querySelector('#sharesAmount');
const commission = document.querySelector('#commissionAmount');
const fee = document.querySelector('#feeAmount');
const max = document.querySelector('#maxGain');
const msg = document.querySelector('.msg');
const exitTable = document.querySelector('#exitTable');
const enterTable = document.querySelector('#enterTable');
let subTotal = 0;
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if (price.value === '' || shares.value === '') {
// alert
msg.classList.add('error');
msg.innerHTML = 'Please enter required fields';
// Remove error after 3 seconds
setTimeout(() => {
msg.classList.remove('error');
msg.innerHTML = '';
}, 3000);
} else {
subTotal = price.value * shares.value;
subTotal = subTotal.toFixed(2)
}
posIndex(subTotal);
negIndex(subTotal);
}
function popList(name) {
let li = document.createElement('li');
li.textContent = name;
li.style.cssText = 'text-align: center'
return li;
}
//finds the 5%-50% loss amounts based on subTotal
function negIndex(num) {
let negPer = -0.05;
let negArray = [];
let i = 0;
exitTable.innerHTML = "";
while (negPer >= -0.50) {
negArray[i] = parseFloat(num * negPer).toFixed(2);
let s = parseFloat(negPer * 100).toFixed(1) + "% " + negArray[i];
let x = popList(s); //creating list elements
exitTable.appendChild(x);
i++;
negPer += -0.05;
}
}
function posIndex(num) {
let posPer = 0.05;
let posArray = [];
let i = 0;
enterTable.innerHTML = "";
while (posPer <= 1.00) {
posArray[i] = parseFloat(num * posPer).toFixed(2);
let s = parseFloat(posPer * 100).toFixed(1) + "% ->" + posArray[i];
let x = popList(s);
enterTable.appendChild(x);
i++;
posPer += 0.05;
}
}
//Listen for form clear
myForm.addEventListener('reset', onReset);
function onReset() {
price.innerHTML = "";
shares.innerHTML = "";
commission.innerHTML = "";
fee.innerHTML = "";
}
<form id="my-form">
<div>
<label for="stockPrice">Stock price</label>
<input type="number" id="stockPrice" />
</div>
<div>
<label for="sharesAmount">Shares amount</label>
<input type="number" id="sharesAmount" />
</div>
<div>
<label for="commissionAmount">Commission amount</label>
<input type="number" id="commissionAmount" />
</div>
<div>
<label for="feeAmount">Fee amount</label>
<input type="number" id="feeAmount" />
</div>
<div>
<label for="maxGain">Max gain</label>
<input type="number" id="maxGain" />
</div>
<div class="msg"></div>
<button type="submit">Submit</button>
</form>
<ul id="exitTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: middle"></ul>
<br>
<ul id="enterTable" style="list-style-type: none; display: flex; flex-direction: column; vertical-align: middle"></ul>

How can I calculate the total value of amount due after choosing different option from drop-down list?

I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.

how to change input text value has been set in javascript

i want asking about javascript. i develop a tax calculation system.
function countsisa(){
var iv = document.getElementById("invoicevalue");
var ppn = document.getElementById("ppn");
var pph = document.getElementById("pph");
var dpp = document.getElementById("dpp");
var propv = document.getElementById("propertyvalue");
var shipv = document.getElementById("shippingvalue");
var dppship = document.getElementById("dppshipping");
var pph23 = document.getElementById("pph23");
var total = document.getElementById("total");
var income = document.getElementById("income");
var ppndoc = document.getElementById("ppndoc");
var pphdoc = document.getElementById("pphdoc");
var pphdoc23 = document.getElementById("pphdoc23");
if(iv.value.replace(/[.*+?^${}()|[\]\\]/g,"") > 0){
document.getElementById("propertyvalue").disabled = true;
document.getElementById("shippingvalue").disabled = true;
document.getElementById("dppshipping").disabled = true;
document.getElementById("pph23").disabled = true;
dpp.value = Math.ceil(iv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
pph.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.015);
ppn.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.10);
income.value = iv.value.replace(/[.*+?^${}()|[\]\\]/g,"")-pph.value-ppn.value;
}else{
if(propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") > 0){
document.getElementById("invoicevalue").disabled = true;
total = parseFloat(propv.value.replace(/[.*+?^${}()|[\]\\]/g,""),10)+parseFloat(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,""),10);
// total = String(total);
propv.value = String(propv.value);
shipv.value = String(shipv.value);
dpp.value = Math.ceil(propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
dppship.value = Math.ceil(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,"") / 1.1);
pph.value = Math.ceil(dpp.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.015);
pph23.value = Math.ceil(dppship.value.replace(/[.*+?^${}()|[\]\\]/g,"") * 0.02);
ppn.value = (propv.value.replace(/[.*+?^${}()|[\]\\]/g,"") - dpp.value)+(shipv.value.replace(/[.*+?^${}()|[\]\\]/g,"")-dppship.value);
income.value = total-pph.value-ppn.value-pph23.value;
}else{
document.getElementById("propertyvalue").disabled = false;
document.getElementById("shippingvalue").disabled = false;
document.getElementById("dppshipping").disabled = false;
document.getElementById("pph23").disabled = false;
}
}
console.log(total);
if(dpp.value <= 0){
dpp.value = 0;
}
if(dppship.value <= 0){
dppship.value = 0;
}
if(pph.value <= 0){
pph.value = 0;
}
if(pph23.value <= 0){
pph23.value = 0;
}
if(ppn.value <= 0){
ppn.value = 0;
}
if(income.value <= 0){
income.value = 0;
}
dppship.value = tandaPemisahTitik(dppship.value);
dpp.value = tandaPemisahTitik(dpp.value);
pph.value = tandaPemisahTitik(pph.value);
pph23.value = tandaPemisahTitik(pph23.value);
ppn.value = tandaPemisahTitik(ppn.value);
pphdoc.value = tandaPemisahTitik(pph.value.replace(/[.*+?^${}()|[\]\\]/g,""));
pphdoc23.value = tandaPemisahTitik(pph23.value.replace(/[.*+?^${}()|[\]\\]/g,""));
ppndoc.value = tandaPemisahTitik(ppn.value);
income.value = tandaPemisahTitik(income.value);
}
this my javascript code to count value and display it in input value.
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="ppn"><?php print _('mi_invoice_ppn'); ?></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<span class="input-group-addon" style="border-radius:0px;">Rp</span>
<input type="text" name="ppn" id="ppn" class="form-control" onkeydown="return numbersonly(this, event);" onkeyup="javascript:tandaPemisahTitik(this);" placeholder="0" />
</div>
</div>
</div>
this is the input code. i want change input text value has been count in javascript function. i want to manually changed again. so javascript function to count automatic. and can edit again if miscalculation.
If you want to recalculate when any input value's changed, you can add change listener on the input elements.
will be look like:
let inputElems = document.querySelectorAll("input");
for (let i = 0, len = inputElems.length; i < len; i++) {
inputElems[i].addEventListener("change", countsisa);
}

Stuck with javascript (beginner)

I have just started learning javascript and i am stuck with my first lab. I have the HTML part working but none of the javascript is working. At first I thought it did not link the javascript code to the HTML code correctly but now i think there is issues with the onload and oninput part. But have no idea why. If someone can help would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
Your Birthday:<input type="date" id="dod"/>
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>
window.onload = function() {
var para = document.getElementById("heading");
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};
I have made a couple of edits:
Missing id on the heading element
typo on the id="dob" you had id="dod"
window.onload = function() {
/******* EDIT 1 ********/
// the heading element has no ID, so you need to add one, or use `querySelector` instead.
//var para = document.getElementById("heading");
var para = document.querySelector("heading");
/***********************/
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
<!-- EDIT 2 -->
<!-- You had a typo on the id of your input 'dod' -> 'dob' -->
<!-- Your Birthday:<input type="date" id="dod"/> -->
Your Birthday:<input type="date" id="dob"/>
<!-- End EDIT -->
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>

Categories