Loop for issue javascript won't run - javascript

So this exercice is about outputing a word by the number typed in the input section simple but i find this problem the loop for won't work if there is any help i will be greatfull
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script defer>
function Verifer() {
var ch = document.querySelector("input").value
var nbr = document.getElementById("nb").value
if ((nbr > 0) && (ch != "")) {
for (let i = 1; i >= nbr; i++) {
var txt = ""
txt += "<h1>" + ch + "</h1> <br>"
document.getElementById("d2").innerHTML = txt
}
} else {
alert("Retype plz")
}
}
</script>
</head>
<body>
// the first input is to type a String //the seconde input to type the number of repetition of this String
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
//This part is dedicated to the output of the function
</div>
</body>

change
var nbr = document.getElementById("nb").value
to
var nbr = parseInt(document.getElementById("nb").value)

Is this what you want to do? Your question is a bit vague.
function Verifer() {
var ch = document.querySelector("input").value;
var nbr = document.getElementById("nb").value;
nbr = parseInt(nbr); //Parse to int
console.log(nbr);
if (nbr === NaN || !ch) { //Validate
document.getElementById("nb").value = "invalid";
return;
}
var txt = ""; //Set var in scope around for loop
for (var i = 1; i <= nbr; i++) { //repeat when i is less or equal to nbr
txt += "<h1>" + ch + "</h1> <br>" //Append txt
}
document.getElementById("d2").innerHTML = txt; //Add txt to element html
}
<strong>Chain :</strong><input type="text" id="chain" maxlength="20"><br>
<strong>nombre de rep :</strong><input type="number" maxlength="5" id="nb"><br>
<button type="button" onclick="Verifer()">Envoyer</button>
<div id="d2">
</div>

Related

I am having trouble getting my function mygame() to run in my Javascript program

I am creating a wheel of fortune like game where a player may have 10 guesses to guess a hidden word and I am using charAt and for loops for the guessing. When I go to click on the button in my html the program will not run.
function myGame()
{
var name = prompt("What is your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = "Today's date is " + d;
var count = 0;
var phrase = "javascriptisneat";
var word = "";
var checkWin = false;
var w_lgth = phrase.length;
var guess;
var correct_guess = false;
for (var i = 0; i < w_lgth; i++)
word = word + "/ ";
document.getElementById("wheel_game").innerHTML = word;
while (checkWin == false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < w_lgth; j++)
{
if(guess == phrase.charAT(j))
{
correct_guess = true;
var set = 2 * j;
word = setCharAt(word, set, guess);
}
}
document.getElementById("wheel_game").innerHTML = word;
checkWin = checkWord(phrase, word);
if(checkWin == true)
{
document.getElementById("game_result").innerHTML = ("you are a winner");
else if (checkWin == false)
{
document.getElementById("game_result").innerHTML = ("You Lose");
if(correct_guess == false)
count = count + 1;
}
}
}
function checkWord(phrase, o_word) { var c_word; c_word = o_word; c_word = o_word.replace(/ /g, ""); if(phrase == c_word) return true; else return false; }
function setCharAt(str, index, chr) { if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>CIS 223 Chapter 7 program</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome Player</h1>
<p> Click to begin </p>
<button type="button" onclick="myGame();">Begin</button>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<div id="wheel_game"> </div> <br>
<div id ="game_result"> </div>
<script src="myScript.js"></script>
</body>
</html>
I tried commenting out parts of the code to see what will run and what won't and it seems that the program will run up until the first else if that is on line 39. After that though the program will not run. I checked and I should have the curly brackets in the right places and am not missing any. I am using a external JavaScript file but I know this should not matter.
You forgot to close the curly braces at line 37 of the if statement. I closed the curly braces and it worked for me

Session storage value showing null

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.

How Resolve Currency IDR in javascript

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.

HTML --- Javascript/JSON

okay here is the question -- .. i tried it but my js isn't working and idk where i am wrong here is the question
THE PROBLEM IS AFTER THE JS EXECUTED IT DOESN'T RUN ... LIKE IDK WHERE THE PROBLEM IS ; I KNOW IT LOADS BUT IT DOES'NT WORK
<html>
<head>
<script src="q2.js" type="text/javascript"> </script>
</head>
<div > Input 1 <input type="text" id ="input1"></div>
<div> Input 2 <input type="text" id ="input2"> </div>
<div> Result <div id="result"> </div></div>
<button onclick= "compute()">Compute</button>
</body>
</html>
the js is here
function compute(){
var n = (document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var i,j;
if (Number(n)){
}
else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)){
}
else {
alert("Error! Please put a valid Number - on input 2 ");
}
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
result.innerHTML += "X";
if(j == (m-1)){
result.innerHTML += "<br />";
}
}
}
}
result.innerHTML += "X";
You forgot to set the variable result:
var result = document.getElementById("result");
And there is a loneley ( in var n = (document.getElementById("input1").value; wich will through syntax error
And you might want to clear the content of your "result"-container when calling the function again: result.innerHMLT = ''
function compute() {
var n = document.getElementById("input1").value;
var m = document.getElementById("input2").value;
var result = document.getElementById("result");
result.innerHMLT = ''
var i, j;
if (Number(n)) {} else {
alert("Error! Please put a valid Number - on input 1 ");
}
if (Number(m)) {} else {
alert("Error! Please put a valid Number - on input 2 ");
}
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
result.innerHTML += "X";
if (j == (m - 1)) {
result.innerHTML += "<br />";
}
}
}
}
<div>Input 1
<input type="text" id="input1">
</div>
<div>Input 2
<input type="text" id="input2">
</div>
<div>Result
<div id="result"></div>
</div>
<button onclick="compute()">Compute</button>

Javascript not working after for loop is done

I can't manage to make the line in the code with all the asterisks to work. Can anyone help? The function works fine, it is just the document.write('This will not print'); that doesn't actually work. What is the problem?
//UPDATE//
First of all, thanks for the quick replies. Now I will post the full code.
As you can see the variable ii is declared at the body.
FULL CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
<!--
function runThis() {
var fruta01 = document.getElementById('fruta').value;
var color01 = document.getElementById('color').value;
var problemo = true;
for (newCount = 0; newCount<=ii; newCount++){
if (storeArray[newCount].match(fruta01) && storeArray[newCount].match(color01)){
document.write(storeArray[newCount]+'<br/>');
problemo = false;
};
};
document.write('This doesnt print')
};
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
//Matriz total
var storeArray = new Array ()
//Numero de objetos
var ii = 0;
//Color de los objetos
var colorCounter = 0
var color = new Array ()
color[0] = 'verde';
color[1] = 'amarillo';
//tipo de objetos
var objectCounter = 0
var object = new Array ()
object[0] = 'limones';
object[1] = 'platanos';
object[2] = 'manzanas';
for (ii; ii<8; ii++) {
storeArray[ii] = 'Tengo ' + ii + ' ' + object[objectCounter] +' de color ' + color[colorCounter];
if (objectCounter != 2) {
++objectCounter
}else{
objectCounter = 0
}
if (colorCounter != 1) {
++colorCounter
}else{
colorCounter = 0
}
}
//print array so that you may see what you can choose...
for(var i=0;i<storeArray.length;i++){
document.write(storeArray[i]+"<br>");
}
//-->
</script>
<form>
Que fruta buscas? <input type="text" size="10" id='fruta'/><br />
De que color? <input type="text" size="10" id='color'/><br />
<input type="submit" value="Submit!" onclick="runThis()"/>
</form>
</body>
</html>
EDIT
The problem is in your for loop
for (newCount = 0; newCount <= ii; newCount++ )
Should be
for (newCount = 0; newCount < ii; newCount++ )
You don't have to put a semicolon after function, and 'if' and 'for' loops.
Here is a better version of your code
function runThis () {
var fruta01 = document.getElementById('fruta').value;
var color01 = document.getElementById('color').value;
var problemo = true;
for (newCount = 0; newCount <= ii; newCount++ )
{
if (storeArray[newCount].match(fruta01) && storeArray[newCount].match(color01) )
{
document.write(storeArray[newCount]+'<br/>');
problemo = false;
}
}
document.write('This will not print'); //**************************
}
Just use console.log() or a simple alert if you want to check just that.
Thats because the loop fails
You never set ii anywhere.
Check your console to make sure there are no javascript errors.

Categories

Resources