We need to make a class called Series with two methods
triNums - function that returns you a triangular series by the number it recives eg: if the function gets 5 - 1, 3, 6, 10, 15
fibNums - function that returns you a fibonacci sequence by the number it
recives eg: if the function gets 5 - 0,1,1,2,3,5
Each of the functions need to be executed when pressing on a button (fibo)(tri) and each element of the result should be displayed on a button
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
addBtns(triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num.value; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
Enter Name <input id="name" placeholder="Enter name"></input>
<button onclick="sayHello()">Click me</button>
<h1 id="hello"></h1>
<input id="num"></input>
<button onclick="tri()">triangular</button>
<div id="feed"></div>
</body>
</html>
You made some mistakes:
you pass #num.value to triNums, which is a Number, and then you try to access its value, which is unneccessary and impossible.
You cannot call tri() as it is part of a Series instance. You could do (new Series).tri() .
Same applies for inner function calls, you must access them via this :
class Series {
tri() {
const num = document.querySelector("#num").value
if (num) {
this.addBtns(this.triNums(num));
}
}
addBtns(arr) {
const feed = document.querySelector("#feed");
var btns = ""; //no buttons by default
for (let v of arr) { //iterate over all values
btns += "<button>" + v + "</button>";
}
feed.innerHTML = btns;
}
triNums(num) {
var triNums = [];
for (let n = 0; n < num; n++) {
triNums[n] = n * (n + 1) / 2;
}
return triNums;
}
triNum(n) {
return (n * (n + 1) / 2);
}
}
function start(){
(new Series).tri();
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title></title>
<script src="home6617.js"></script>
</head>
<body>
<div id="feed"></div>
<input id="num" />
<button onclick="start()">Start</button>
</body>
</html>
Related
I keep on getting null every time I try to store values in Section B and C but works fine for A. I can't seem to find where the issue is. I am trying to have a user's info display on a different page based on the section he chooses. If the user chooses section B for example I would want to let the user know on the next page that he/she has ordered a seat in Section B and whatever the available seat is along with the name and price. After the boarding pass is displayed on the next page, I want the array to change from having 5 seats to 4 and keep this array updated everytime a new person signs up.
index.html
<!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 = "airplane.js"></script>
</head>
<style>
</style>
<body>
<h1>Welcome To Air France</h1>
<h2>Choose your seat section here</h2>
<h3>Section A</h3>
<p>Price:</p>
<div id = "Section1Price"></div>
<div id = "Section1"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameA" type="text" size="25" height="25">
<input id = "bookSeatA" type="button" onclick="location.href='bookingPage.html';" value="Book a Seat in Section A" />
</form>
<h3>Section B</h3>
<p>Price:</p>
<div id = "Section2Price"></div>
<div id = "Section2"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameB" type="text" size="25" height="25">
<input id = "bookSeatB" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section B">
</form>
<h3>Section C</h3>
<p>Price:</p>
<div id = "Section3Price"></div>
<div id = "Section3"></div>
<form action = "bookingPage.html" method="post">
<p>Enter your full name to book in this section:</p>
<input id="clientNameC" type="text" size="25" height="25">
<input id = "bookSeatC" type = "button" onclick="location.href='bookingPage.html';" value = "Book a Seat in Section C">
</form>
</body>
</html>
airplane.js
function start()
{
var price1;
price1 = Math.random() * (200 - 100) + 100;
price1 = price1.toFixed(2);
var price2 = (Math.random() * (300 - 100) + 100).toFixed(2);
var price3 = (Math.random() * (300 - 100) + 100).toFixed(2);
var priceArray = [price1, price2, price3];
var sectionASeats = [];
var sectionBSeats = [];
var sectionCSeats = [];
for (var k = 0; k < 5; k++)
{
sectionASeats[k] = 0;
sectionBSeats[k] = 0;
sectionCSeats[k] = 0;
}
var buttonA = document.getElementById( "bookSeatA" );
buttonA.addEventListener( "click", function() {bookSeat(sectionASeats)}, false );
buttonA.addEventListener("click",function(){handleSubmitA(priceArray[0],sectionASeats,"A")}, false );
var buttonB = document.getElementById( "bookSeatB" );
buttonB.addEventListener( "click", function() {bookSeat(sectionBSeats)}, false );
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
var buttonC = document.getElementById( "bookSeatC" );
buttonC.addEventListener( "click", function() {bookSeat(sectionCSeats)}, false );
buttonC.addEventListener("click",function(){handleSubmitC(priceArray[2]),sectionCSeats,"C"}, false );
var result1 = "";
var result2 = "" ;
var result3 = "" ;
result1 += checkSection(sectionASeats, "A" );
result2 += checkSection(sectionBSeats, "B" );
result3 += checkSection(sectionCSeats, "C" );
priceArray.sort(function(a,b) {return a-b});
document.getElementById("Section1Price").innerHTML = "$" + priceArray[0];
document.getElementById("Section1").innerHTML = result1;
document.getElementById("Section2Price").innerHTML = "$" + priceArray[1];
document.getElementById("Section2").innerHTML = result2;
document.getElementById("Section3Price").innerHTML ="$" + priceArray[2];
document.getElementById("Section3").innerHTML = result3;
}
function sectionSeatNum (array)
{
for (var i = 0; i < array.length;i++)
{
if (array[i] == 1)
{
return i+1;
}
}
}
function handleSubmitA(priceForA,array,section)
{
const name = document.getElementById("clientNameA").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForA);
return;
}
function handleSubmitB(priceForB,array,section)
{
const name = document.getElementById("clientNameB").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForB);
return;
}
function handleSubmitC(priceForC,array,section)
{
const name = document.getElementById("clientNameC").value;
var seatNumber = sectionSeatNum(array);
sessionStorage.setItem("ARRAY", JSON.stringify(array));
sessionStorage.setItem("SECTION", section);
sessionStorage.setItem("SEATNUM", seatNumber);
sessionStorage.setItem("NAME", name);
sessionStorage.setItem("PRICE", priceForC);
return;
}
function bookSeat(array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i] == 0)
{
array[i] = 1;
break;
}
}
}
function checkSection(array, section)
{
var result;
var check = true;
var emptyCounter = 0;
var takenCounter = 0;
for (var i = 0;i<array.length;i++)
{
if(array[i] == 0)
{
emptyCounter++;
}
else{
takenCounter++;
}
}
if(takenCounter == array.length)
{
check = false;
result = "<p>There are no seats available in Section " + section + ".</p>";
}
else{
check = true;
result = "<p>There are " + emptyCounter + " seats available in Section " + section + ".</p>";
}
return result;
}
window.addEventListener("load", start,false);
bookingPage.html
<!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 = "booking.js"></script>
</head>
<body>
<h1>Thank you for choosing Air France</h1>
<h2>Here is your boarding pass</h2>
<h3 id="booking-name"></h3>
<form action="index.html" method="get">
<input id = "backToHome" type="button" onclick="location.href='index.html';" value="Return to Homepage">
</form>
</body>
</html>
booking.js
function start()
{
const name = sessionStorage.getItem("NAME");
const price = sessionStorage.getItem("PRICE");
const arrayBookings = JSON.parse(sessionStorage.getItem("ARRAY"));
const section = sessionStorage.getItem("SECTION");
var seatNum = sessionStorage.getItem("SEATNUM")
var result = "";
result += "<p> Thank you " +name+ " for flying with us. Here is your boarding pass.</p>";
result += "<p> Name: " + name + "</p>";
result += "<p> Section: "+ section + "</p>";
result += "Price: $"+price;
result += "<p>Seat number: "+seatNum+ "</p>";
// result += "<p>"+arrayBookings+"</p>";
document.getElementById("booking-name").innerHTML = result;
}
window.addEventListener("load", start, false);
You have typo here
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1]),sectionBSeats,"B"}, false );
while you want to have
buttonB.addEventListener("click",function(){handleSubmitB(priceArray[1],sectionBSeats,"B")}, false );
Session C is the same error.
I'm trying to create a dice rolling app that utilizes user input as the arguments for the function. I want to be able to enter the number of sides the dice should have, as well as how many dice should be rolled. For example, the user should be able to roll 5, 6-sided dice...or 2, 8-sides dice...etc...the two variables are up to the user to decide and input into the form. I've written some code with a "Dice Class" and a couple of functions which work when the two variables are hard coded. The problem is that for some reason the function cannot read the user input.
HTML
<!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="dicex.css" />
<title>Dice</title>
</head>
<body>
<div class="container">
<form id="form" class="form" onsubmit="return false">
<h2>Dice Roller</h2>
<div class="form-control">
<input type="number" id="sides" placeholder="How many sides?" />
</div>
<div class="form-control">
<input type="number" id="quantity" placeholder="How many dice?" />
</div>
<div class="form-control">
<p id="results">My Results Go Here</p>
</div>
<button id="roll">Roll</button>
</form>
</div>
<script src="dice.js"></script>
</body>
</html>
Javascript
// Query Selectors
let sides = document.querySelector("#sides").value;
let quantity = document.querySelector("#quantity").value;
let results = document.querySelector("#results");
let roll = document.querySelector("#roll");
// Dice Class
class Die {
constructor(sides) {
this.sides = sides;
}
roll() {
let random_side = Math.floor(Math.random() * this.sides) + 1;
return random_side;
}
}
// Dice Roll Function
let create = function (e) {
let a = [];
for (let i = 0; i < 5; i++) {
let n = new Die(6);
let r = n.roll();
a.push(r);
}
let sum = a.reduce((a, b) => a + b);
results.textContent = `You rolled ${a} for a total of ${sum}!`;
e.preventDefault();
};
// Event Listeners
roll.addEventListener("click", create);
Use them inside the create function... which is triggered by an event.
// Query Selectors
//let sides = document.querySelector("#sides").value;
//let quantity = document.querySelector("#quantity").value;
let results = document.querySelector("#results");
let roll = document.querySelector("#roll");
// Dice Class
class Die {
constructor(sides) {
this.sides = sides;
}
roll() {
let random_side = Math.floor(Math.random() * this.sides) + 1;
return random_side;
}
}
// Dice Roll Function
let create = function (e) {
let a = [];
// Here
let sides = document.querySelector("#sides").value;
let quantity = document.querySelector("#quantity").value;
for (let i = 0; i < quantity; i++) { // use here
let n = new Die(sides); // and here
let r = n.roll();
a.push(r);
}
let sum = a.reduce((a, b) => a + b);
results.textContent = `You rolled ${a} for a total of ${sum}!`;
e.preventDefault();
};
// Event Listeners
roll.addEventListener("click", create);
So my problem is that putting onclick="main()" onto a button doesn't work but something like onclick="alert('test')" does work. When I look in the console, it throws Uncaught ReferenceError: main is not defined when I press the button.
I have tried putting all the functions that aren't main() inside of main() but that didn't work. I've also tried putting semicolons after all the functions thinking that I just made up the fact that you don't have to put a semicolon after a function.
I'm confused because I copy/pasted another JavaScript program of mine and edited it to make this and that one works fine.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
<style>
/*----- START OF STYLESHEET -----*/
*, :before, :after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/*body {
margin : 0;
*/}
/*-----END OF STYLESHEET-----*/
</style>
<script>
//----- START OF SCRIPT -----//
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shuffle-list() {
for(var shuffleent = 0; shuffleent > list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display-list() {
var state = "";
for(displayent = 0; displayent > list.length; displayent = displayent + 1) {
for(displayentvalue = 0; displayentvalue > list[displayent]; displayentvalue = displayentvalue + 1) {
state = state + "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
Sleep(1000);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display-list();
// Shuffle sorted list
// Sort
//while(isSorted === false) {
//}
}
//-----END OF SCRIPT-----//
</script>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
some error in you code:
"}"
'-' in the function name.
after fixed the error, the code worked
You should not use a - while naming your function but instead you can use these.
An underscore and replace the -.
display-list() to display_list()
Use CamelCase.
display-list() to displayList().
Function names can contain letters, digits, underscores, and dollar signs but not dash
sign
There are so many mistakes in your code.
There is no Sleep function in the JS.
You can't have - or whitespaces in the function names.
You are never going to enter in this loop for(displayent = 0; displayent > list.length; displayent = displayent + 1) you had to use < instead >
Where are you using valuecount and isSorted
In the CSS } which shouldn't be there
I edited some of your code to make it work.
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
var swapent;
swapent = list[value1];
list[value1] = list[value2];
list[value2] = swapent;
}
// Shuffle list
function shufflelist() {
for (var shuffleent = 0; shuffleent < list.length; shuffleent = shuffleent + 1) {
swap(shuffleent, randint(0, list.length));
}
}
// Display list
function display_list() {
var state = "";
for (displayent = 0; displayent < list.length; displayent = displayent + 1) {
for (displayentvalue = 0; displayentvalue < list[displayent]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state = state + "<br>"
}
document.getElementById("output").innerHTML = state;
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
Re Wrote the logic of your code
// I can't believe I have to implement this myself
function randfloat(min, max) {
return Math.random() * (max - min) + min;
}
function randint(min, max) {
return Math.round(randfloat(min, max));
}
// List
var list = [];
// Swap two entries
function swap(value1, value2) {
list[value2] = [list[value1], list[value1] = list[value2]][0];
}
// Shuffle list
function shufflelist() {
list.forEach((element, index) => {
swap(index, randint(0, list.length))
})
}
// Display list
function display_list() {
var state = "";
list.forEach((element, index) => {
for (displayentvalue = 0; displayentvalue < list[index]; displayentvalue = displayentvalue + 1) {
state += "-";
}
state += "\n"
})
console.log(state);
}
function main() {
// Number of values
var valuecount = document.getElementById("values").value;
// Self-explanatory
var isSorted = false;
alert("working");
// Generate presorted list
list = [0, 1, 2, 3];
display_list();
shufflelist();
display_list();
}
*,
:before,
:after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>The Worst Sorting Algorithm Ever Made</title>
</head>
<body>
<h1>The Worst Sorting Algorithm Ever Made</h1>
<form>
<label for="values">Number of equally spaced values:</label><br>
<input type="number" id="values" name="values"><br><br><br>
<input type="button" id="start" value="Start" onclick="main()"><br><br><br>
</form>
<p id="output"></p>
</body>
</html>
<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
function chkInput(){
var n = parseInt(n1)
var a,b,r;
a = 0;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
</script>
</head>
<body>
<input type="text"
id="n1">
<input type="button"
value="Enter"
onclick="chkInput(n1.value)">
</body>
</html>
I'm new to JavaScript and I've been attempting to construct a code for finding the Nth term of the Fibonacci Sequence where the User inputs a number and the sequence runs until the nth number. I have been tasked with using both a function and a for loop for this. However when I run it, no matter what number I input it returns as 1. My questions is why that might be? I'm a student so I just need general direction not the answer. This snippet is what I have so far.
You weren't capturing the text input value as a parameter.
You had:
checkInput()
It should be
chkInput(n1)
So your line
var n = parseInt(n1);
Was parsing undefined, so the value of n is now NAN (Not a Number), so the for loop never got executed.
function chkInput(n1) {
var n = parseInt(n1);
var a, b, r;
a = 0;
b = 1;
r = 1;
for (var i = 2; i <= n; i++) {
r = a + b;
a = b;
b = r;
}
alert(r);
}
<input type="text" id="n1">
<input type="button" value="Enter" onclick="chkInput(n1.value)">
You have almost done with your assignment.
You have missed to receive the value in the function definition.
Altering function chkInput(){ to function chkInput(n1){ will complete your assignment.
Find the your working code snippet below.
<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
function chkInput(inputValue) {
var n = parseInt(inputValue)
var a,b,r;
a = 0;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
</script>
</head>
<body>
<input type="text" id="n1">
<input type="button" value="Enter" onclick="chkInput(n1.value)">
</body>
</html>
You need to get value of element using DOM functions like document.getElementById("n1").value
Also your algorithm is wrong it should have a = 1;
function chkInput(){
var n = parseInt(document.getElementById("n1").value)
var a,b,r;
a = 1;
b = 1;
r = 1;
for(var i = 2; i <= n; i++){
r = a + b;
a = b;
b = r;
}
alert (r);
}
<!DOCTYPE HTML>
<html>
<title>Fibonacci Assignment</title>
<head>
<script>
</script>
</head>
<body>
<input type="text"
id="n1">
<input type="button"
value="Enter"
onclick="chkInput(n1.value)">
</body>
</html>
How can resolve script like this ?
for example count or minus Variable A and Variable B in currency IDR
thanks, anyone can help me ...
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>
</body>
</html>
here code javascript function :
<script type="text/javascript">
function formatangka_titik()
{
a = form1.harga.value;
b = a.replace(/[^\d]/g,"");
c = "";
panjang = b.length;
j = 0;
for (i = panjang; i > 0; i--)
{
j = j + 1;
if (((j % 3) == 1) && (j != 1))
{
c = b.substr(i-1,1) + "." + c;
} else {
c = b.substr(i-1,1) + c;
}
}
form1.harga.value = c;
</script>
I think your problem is that you are adding two strings together, which will concatenate the strings instead of add the numeric values.
Example adding string types:
var a = '1';
var b = '2';
console.log(a + b); // prints '12' to the console
Example adding int types:
var a = 1;
var b = 2;
console.log(a + b); // prints '3' to the console
JavaScript is loosely typed, so it's not always immediately apparent what a variable's type is.
You can do a few things to change a string-type variable to an int.
Here are a couple common ways:
var stringNum = '123';
var intNum1 = parseInt(stringNum, 10);
var intNum2 = +stringNum;
Specifically, your code would need to look something like this:
function formatangka_titik() {
var a = form1.harga.value.replace(/[^\d]/g, "");
var b = form1.diskon.value.replace(/[^\d]/g, "");
var a = +a; // converts 'a' from a string to an int
var b = +b; // converts 'b' from a string to an int
form1.harga.value = formatNum(a);
form1.diskon.value = formatNum(b);
form1.bayar.value = formatNum(+a + b);
}
function formatNum(rawNum) {
rawNum = "" + rawNum; // converts the given number back to a string
var retNum = "";
var j = 0;
for (var i = rawNum.length; i > 0; i--) {
j++;
if (((j % 3) == 1) && (j != 1))
retNum = rawNum.substr(i - 1, 1) + "." + retNum;
else
retNum = rawNum.substr(i - 1, 1) + retNum;
}
return retNum;
}
<form name="form1">
<input id="harga" onkeyup="formatangka_titik()" type="text" />
<input id="diskon" onkeyup="formatangka_titik()" type="text" />
<input id="bayar" onkeyup="formatangka_titik()" type="text" />
</form>
In above example how we can calculate percentage for IDR currency.