This is my JavaScript-Code
it should calculate how much CO2 produces a person per km. it is a school subject an i am just at the beginning so please go easy on me...
also i just registered to stockoverflow
i am also a newbee here...i thank you in advance...
window.onload = function () {
// CO2 Verbrauch = ((fs / ksv) * ta) / am)+(fs*0.14)
var btn = document.getElementById('btn'); // Initiate Calulation
var ta = document.getElementById('treibstoffart') // Selector
var benzin = document.getElementById('benzin'); // Option 1
var diesel = document.getElementById('diesel'); // Option 2
var autogas = document.getElementById('autogas'); // Option 3
var ksv = document.getElementById('Kraftstoffverbrauch'); // Inputfield
var fs = document.getElementById('Fahrtstrecke'); // Inputfield
var am = document.getElementById('Anzahl der Mitfahrer'); // Inputfield
var ausgabe = document.getElementById('ergebnis'); // Result
every option has a fixed number
var tsa = function () { //////// NOT SURE WHAT IS WRONG
if (benzin) {
benzin.value = 2.33;
} else if (diesel) {
diesel.value = 2.64;
} else if (autogas) {
autogas.value = 1.64;
}
}; // End of function (treibstoffart)
btn.onclick = function () {
ausgabe.innerText = (((fs.value * 1 / ksv.value * 1) * tsa) / am.value * 1) + (fs.value * 0.14); //////// TSA is added here
};
} // End of function (window.onload)
This is the HTML Code
i am using Bootstrap as you can see but i think the most problem is the selector i use for the function.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Übung 1 Rechner</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="uebung_1.css">
<script src="uebung_1.js"></script>
</head>
<body>
<section>
<form class="form-inline">
<select id="treibstoffart" class="form-control">
<option value="" selected>... auswählen ...</option>
<option value="benzin">Benzin</option>
<option value="diesel">Diesel</option>
<option value="autogas">Autogas</option>
<input id="Kraftstoffverbrauch" type="text" placeholder="Kraftstoffverbrauch (Liter/100km)" value=""
class="form-control">
<input id="Fahrtstrecke" type="text" placeholder="Fahrtstrecke (in km)" value="" class="form-control">
<input id="Anzahl der Mitfahrer" type="text" placeholder="Anzahl der Mitfahrer" value=""
class="form-control">
<button type="button" id="btn" class="btn btn-primary" value="">Berechnen</button>
<button type="reset" class="btn btn-danger" value="Reset">Clear</button>
</form>
</section>
<section>
<p>Das Ergebnis wird hier Angezeigt</p>
<p id="ergebnis"></p>
<p>Weitere Ergebnisse für Reisebus, Bahn, Flugzeug</p>
</section>
</body>
</html>
if have found the answer
window.onload = function () {
// CO2 Verbrauch = ((fs / ksv) * ta) / am)+(fs*0.14)
let btn = document.getElementById('btn');
let ausgabe = document.getElementById('ergebnis'); // Result
let ta = document.getElementById('treibstoffart'); // Selector
let ksv = document.getElementById('Kraftstoffverbrauch'); // Inputfield
let fs = document.getElementById('Fahrtstrecke'); // Inputfield
let am = document.getElementById('Anzahl der Mitfahrer'); // Inputfield
btn.onclick = function () { // Initiate Calulation
ausgabe.innerText = (((fs.value * 1 / ksv.value * 1) * ta.value) / am.value * 1) + (fs.value * 0.14);
};
} // End of function (window.onload)
Related
I have a script like this
let x;
let y;
let z;
let obliczone;
document.getElementById("srednia").onclick = function() {
x = document.getElementById("grade1").value;
y = document.getElementById("grade2").value;
z = document.getElementById("grade3").value;
x = Number(x);
y = Number(y);
z = Number(z);
obliczone = Number(obliczone);
obliczone = (x + y + z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
<!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="main.css">
<title>Document</title>
</head>
<body>
<label>Ocena 1</label> <input type="text" id="grade1"><br>
<label>Ocena 2</label> <input type="text" id="grade2"><br>
<label>Ocena 3</label> <input type="text" id="grade3"><br>
<label>Oblicz: </label> <button id="srednia">Średnia</button>
<p id="wynik"></p>
<script src="index.js"></script>
</body>
</html>
and if user type in a number with "+" like 2+ I want i to give me 2.5 value and if the input is higher than 6 to break the function. It meant to calculate arithmetic mean of 3 digits and as I wrote earlier it should change ex. 1+ to 1.5
By default when the JavaScript interpreter tries to cast the string to a number and this string contains a symbol it results in a NaN (Not a Number). You can do what you want by replacing the '+' symbol with '.5'.
The new code:
let x;
let y;
let z;
let obliczone;
document.getElementById("srednia").onclick = function () {
x = document.getElementById("grade1").value;
y = document.getElementById("grade2").value;
z = document.getElementById("grade3").value;
const doesXEndsWithPlus = x.endsWith('+')
const doesYEndsWithPlus = y.endsWith('+')
const doesZEndsWithPlus = z.endsWith('+')
if (doesXEndsWithPlus) x = x.replace('+', '.5')
if (doesYEndsWithPlus) y = y.replace('+', '.5')
if (doesZEndsWithPlus) z = z.replace('+', '.5')
x = Number(x);
y = Number(y);
z = Number(z);
obliczone = Number(obliczone);
obliczone = (x + y + z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
This is one way you can do it however if you end up putting more than 3 inputs it can start getting repetitive.
document.getElementById("srednia").onclick = function(){
let obliczone;
let x = document.getElementById("grade1").value;
let y = document.getElementById("grade2").value;
let z = document.getElementById("grade3").value;
if (x.includes('+')) {
x = parseFloat(x.split("+")[0] + ".5")
}
if (y.includes('+')) {
y = parseFloat(y.split("+")[0] + ".5")
}
if (z.includes('+')) {
z = parseFloat(z.split("+")[0] + ".5")
}
obliczone = (x+y+z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
One solution to make it cleaner and more dynamic is to create a helper function formatNumInput(input):
function formatNumInput(input) {
let newNum;
if (input.includes('+')) {
newNum = parseFloat(input.split("+")[0] + ".5")
} else {
newNum = parseFloat(input)
}
return newNum
}
document.getElementById("srednia").onclick = function(){
let obliczone;
let x = document.getElementById("grade1").value;
let y = document.getElementById("grade2").value;
let z = document.getElementById("grade3").value;
x = formatNumInput(x)
y = formatNumInput(y)
z = formatNumInput(z)
obliczone = (x+y+z) / 3;
console.log(obliczone);
document.getElementById("wynik").innerHTML = "Twoja średnia to " + obliczone;
}
I would like to propose you something a little bit different that could to inspired you and where are not you are not limited only to 3 values of ratings:
//here I define some globals variables
let evaluation = document.getElementById('eval');
let evaluations = [];
let showEval = document.getElementById("evaluation");
let addEval = document.getElementById("addEval");
let average = 0
function showEvals (){
for (let i = 0; i < evaluations.length; i++) {
showEval.innerHTML += `<span>${evaluations[i]}</span>, `
};
};// this is a function to show ratings
function countAverage () {
let sum = 0
for (let i = 0; i < evaluations.length; i++) {
const rating = parseFloat(evaluations[i],10)//here I convert a string go float (Numners() create variable type object not type number
sum += rating
average = (sum/evaluations.length).toFixed(2)// I limited my float to 2 digits
};
document.getElementById("result").innerHTML = "Twoja średnia to " + average
} // this function counts and shows average
addEval.onclick = function(){
evaluations.push(evaluation.value)
showEval.innerHTML = [];
showEvals();
countAverage();
};// here new rangs is pushed to the array of evaluations and it calls ather functions
<!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">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<!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">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<label for="eval">Dodaj ocene:</label>
<select name="evals" id="eval">
<option value="1">1</option>
<option value="1.5">1+</option>
<option value="2">2</option>
<option value="2.5">2+</option>
<option value="3">3</option>
<option value="3.5">3+</option>
<option value="4">4</option>
<option value="4.5">4+</option>
<option value="5">5</option>
<option value="5.5">5+</option>
<option value="6">6</option>
</select>
</select>
<button id="addEval">Dodaj ocene</button>
<h2>Twoje oceny to:</h2>
<div id="evaluation"></div>
<p id="result"></p>
</body>
</html>
So I am trying to practice javascript and so I'm trying to do a small javascript code in which a random number is generated whenver the page loads and then the user has the option of subtracting or adding 10 from that number. The user can also input any text in the textfield and the text there will be displayed with the answer. For ex: if the random number generated is 100 and the user choose the 'subtract 10' option and wrote 'Hello' in the text field, the output will be '90Hello'.
I did most of the code, but I can't figure out how to display the answer because it doesn't work for some reason. The random number is shown but the add and subtract buttons are not working. Can someone help with that?
The code till now is:
count = 0;
let y = Math.floor(Math.random() * 100) + 1;
y = document.getElementById("numb").innerHTML;
function subtractTen() {
var t1 = document.getElementById("te");
var n1 = document.getElementById("numb") * 10;
var subtract = Number(n1.value);
var ans = subtract + t1;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function addTen() {
var t2 = document.getElementById("te");
var n2 = document.getElementById("numb") / 10;
var add = Number(n2.value);
var ans = add + t2;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function reset() {
count = countN * 0;
var res = document.getElementById("numb");
res.innerHTML = count;
}
<html>
<head>
<title></title>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen();" value="sub" /> Subtract 10 </button>
<button onClick="addTen();" value="add" /> Add 10 </button>
<button onClick="reset();" value="res" /> Reset </button>
<br />
<input name="text" id="te" />
<span id="numb" id="answer"></span>
</body>
</html>
//script.js
const container = document.getElementById('answer');
let num = generateRandom(1, 200)
let inputText = '';
function changeText() {
inputText = document.getElementById('te').value
container.innerText = inputText + num;
}
function generateRandom(min, max) {
return Math.floor(Math.random() * (max-min) + min);
}
function subtractTen() {
num -= 10;
container.innerText = inputText+num;
}
function addTen() {
num += 10;
container.innerText = inputText+num;
}
function reset() {
num = generateRandom(1, 200);
container.innerText = num
inputText = '';
document.getElementById('te').value = ''
}
container.innerText = num;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen()" value="sub" /> Subtract 10 </button>
<button onClick="addTen()" value="add" /> Add 10 </button>
<button onClick="reset()" value="res" /> Reset </button>
<br />
<input oninput="changeText()" name="text" id="te" />
<span id="answer"></span>
</body>
</html>
i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does'nt stop when i press stop i want to clear the interval that i named with myTimer if i didn't put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.
const // my variable
myHour = document.getElementById("hours"),
myMin = document.getElementById("min"),
mySecond = document.getElementById("second"),
myMiliSecond = document.getElementById("dsecond"),
startchrono = document.getElementById("start"),
getLap = document.getElementById("lap"),
stopchrono = document.getElementById("stop"),
resetchrono = document.getElementById("reset"),
result = document.getElementById("result");
let // variable
milisecond = 0,
second = 0,
minute = 0,
hour = 0,
chronoRun = false,
round = 0;
function decoration(item) // this function is for add 0 if second or minute less than 10
{
if (String(item).length < 2) {
item = "0" + item;
}
return item;
}
function lapset() // function that create a new row in the table to save rounds
{
round++;
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
if (round <= 10) {
const // insert the row in table
tr = result.insertRow(-1);
tr.insertCell(0).innerHTML = round;
tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
} else if (round <= 11) {
tr = result.insertRow(-1);
tr.insertCell(-0).innerHTML = "-";
tr.insertCell(-1).innerHTML = "you can't add any more laps";
getLap.setAttribute("disabled", "true");
}
}
function chrono() //chrono start
{
// chrono
milisecond++;
// make sure that minute, second have to be less than 60
if (milisecond > 10) {
milisecond = 0;
second++;
}
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
myMiliSecond.innerHTML = ds;
mySecond.innerHTML = s;
myMin.innerHTML = m;
myHour.innerHTML = h;
startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
setInterval(chrono, 100);
};
const test = () => {
return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!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" />
<title>Document</title>
</head>
<body>
<div id="chrono">
<div id="timer">
<span id="hours" class="time">00</span>
<span class="sep">:</span>
<span id="min" class="time">00</span>
<span class="sep">:</span>
<span id="second" class="time">00</span>
<span class="sep">:</span>
<span id="dsecond" class="time">00</span>
</div>
<div id="btnarea">
<button id="start" class="btnevent">start</button>
<button id="lap" class="btnevent">lap</button>
<button id="stop" class="btnevent">stop</button>
<button id="reset" class="btnevent">reset</button>
</div>
<table id="result">
<caption>saved lap</caption>
<tbody>
<tr>
<th class="round">round</th>
<th class="laptime">time</th>
</tr>
</tbody>
</table>
</div>
<script src="newpagescript.js"></script>
</body>
</html>
and that is my html code i think every is ok with my code but if there any issue i am looking for adives
You need to get the return value of the setInterval function and then pass that value as a parameter in the clearInterval function. For example, see below:
`// function chronoStarts() {}
let intervalId = 0;
const myTimer = () => {intervalId = setInterval(chrono, 100);};
const test = () => {
clearInterval(intervalId);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);`
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")
//}
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>