Problem with modifying JavaScript/HTML code - javascript

I've got a problem with modifying my code. I need to edit my code so it will not only do its purpose (the thing that it does now) but it will count from 1 to given number.
The code is in Polish and it's simple. It's purpose for now is to calculate the factorial of given number.
Here's the code:
function obliczSilnie(liczba) {
var wynik = silnia(liczba);
if (wynik > 0) {
document.getElementById("result").innerHTML =
"<h3 style'color:blue;'>Silnia liczby " + liczba +
"wynosi: " + wynik + "</h3>";
}
}
function silnia(liczba) {
if (liczba == 0 || liczba == 1) {
return 1;
} else if (liczba < 0) {
error();
return -1;
}
var wynik = liczba * silnia(liczba - 1);
return wynik;
}
function error() {
document.getElementById("result").innerHTML =
"<h3 style='color:red;'>Błąd: Nie można obliczyć silni dla liczby ujemnej! </h3>";
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Obliczanie silni</h1>
<form name="myForm">
<p> <b>Podaj liczbę:</b>
<input type="number" name="myNumber" value="0" size=2> </p>
<input type="reset" value="Wyczyść">
<input type="button" value="Obilcz" onclick="obliczSilnie(document.myForm.myNumber.value)">
</form>
<p id="result"></p>
</body>
</html>

I hope I understood your question correctly. That's my solution:
function computeFactors(number) {
//Here we use recursion with a for loop
for(var i = 1;i < number;i++){
var result = factorial(i);
if (result > 0) {
document.getElementById("result").innerHTML +=
"<h3 style='color:blue;'> Factorial of " + i +
" is: " + result + "</h3>";
}
}
}
function factorial(number) {
if (number == 0 || number == 1) {
return 1;
} else if (number < 0) {
error();
return -1;
}
var result = number * factorial(number - 1);
return result;
}
function error() {
document.getElementById("result").innerHTML =
"<h3 style='color:red;'>Error: Could not factorize a negative number! </h3>";
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Factory calculation</h1>
<form name="myForm">
<p> <b>Enter a number:</b>
<input type="number" name="myNumber" value="0" size=2> </p>
<input type="reset" value="Clear">
<input type="button" value="Calculate" onclick="computeFactors(document.myForm.myNumber.value)">
</form>
<p id="result"></p>
</body>
</html>

Related

HTML5 Progress Bar not working

I look for similar question pertaining to my problem but couldn't fine any solution to it. I was doing an example of progress bar in HTML5, I tried IE and Chrome but the GO button isn't setting the progress bar in motion.
Here is the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>HTML5 Progress Bar</title>
<script type="text/javascript">
function go();
{
var inc = 0;
var doIt = setInterval(updateProgress,50);
function updateProgress()
{
inc++;
if (inc > 100)
{
document.getElementById("output").innerHTML = "Done!";
} else
{
document.getElementById("output").innerHTML = inc+ "%";
document.getElementById("progress1").value = inc;
}
}
}
</script>
</head>
<body>
<progress id = "progress1" value="0" min="0" max="100" style="width:300px;"> </progress> <br>
<span id="output"> </span> <br> <br>
<button id= "go" onclick="go()"> GO </button>
</body>
</html>
That's because there is a semicolon ; after your go function before your curly braces start. Try running the snippet below.
function go() {
var inc = 0;
var doIt = setInterval(updateProgress, 50);
function updateProgress() {
inc++;
if (inc > 100) {
document.getElementById("output").innerHTML = "Done!";
} else {
document.getElementById("output").innerHTML = inc + "%";
document.getElementById("progress1").value = inc;
}
}
}
<progress id="progress1" value="0" min="0" max="100" style="width:300px;"> </progress> <br>
<span id="output"> </span> <br> <br>
<button id="go" onclick="go()"> GO </button>
The issue is that you have a semicolon ; after go();, it should look like
function go()
{
var inc = 0;
var doIt = setInterval(updateProgress,50);
function updateProgress()
{
inc++;
if (inc > 100)
{
document.getElementById("output").innerHTML = "Done!";
} else
{
document.getElementById("output").innerHTML = inc+ "%";
document.getElementById("progress1").value = inc;
}
}
}

Want to make it so prices actually reflect the choices

Hope everyone is having a good weekend!
If you select a Small Cheese pizza the price comes out to $5. However, if you select a Small Cheese and Peanut Butter, it still comes out to $5. I think I might need to add a loop/array. I am definitely missing something. Thanks for your help. Also, I am a total newbie to all of this so no answers that are may seem out of knowledge based off what I have written. Thanks!
var pizzaPrice = 0;
function Pizza(size,toppings,pizzaPrice) {
this.size = size;
this.toppings = toppings;
this.pizzaPrice = 0;
}
Pizza.prototype.price = function() {
if (this.size === "Small") {
this.pizzaPrice += 2;
}
else if (this.size === "Medium") {
this.pizzaPrice += 3;
}
else if (this.size === "Large") {
this.pizzaPrice += 4;
}
if (this.toppings === "Cheese") {
this.pizzaPrice += 3;
}
else if (this.toppings === "Cheese" && this.toppings === "Peanut Butter") {
this.pizzaPrice += 10;
console.log("hey");
}
else if (this.toppings === "Vegetarian") {
this.pizzaPrice += 2;
}
else if (this.toppings === "Supreme") {
this.pizzaPrice += 4;
}
else if (this.toppings === "Pepperoni") {
this.pizzaPrice += 3;
}
return this.pizzaPrice;
}
$(document).ready(function(){
$("form#pizza").submit(function(event){
event.preventDefault();
var size = $("input[type=radio][name=size]:checked").val();
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
var newPizza = new Pizza(size,toppings,pizzaPrice);
newPizza.price();
$("#responses").append("<li>" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Pizza Pizza</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.2.0.js"></script>
<script src="js/scripts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>Pizza Toppings</h2>
</div>
<form id="pizza">
<div class="form-group">
<p>What size would you like your pizza:</p>
<input type="radio" name="size" value="Small">Small.<br>
<input type="radio" name="size" value="Medium">Medium.<br>
<input type="radio" name="size" value="Large">Large.<br>
</div>
<div class="form-group">
<p>Which toppings would you like</p>
<input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
<input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
<input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
<input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
<input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
<input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
<input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
<input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
</div>
<button type="submit">Let's get your order</button>
</form>
<ul id="responses">
</ul>
</div>
</body>
</html>
Firstly, you need to get values of all checked toppings in an array, currently you are getting only the first one. Then you need to add prices for each topping selected while calculating the price. you can use indexOf for this:
var pizzaPrice = 0;
function Pizza(size,toppings,pizzaPrice) {
this.size = size;
this.toppings = toppings;
this.pizzaPrice = 0;
}
Pizza.prototype.price = function() {
if (this.size === "Small") {
this.pizzaPrice += 2;
}
else if (this.size === "Medium") {
this.pizzaPrice += 3;
}
else if (this.size === "Large") {
this.pizzaPrice += 4;
}
if (this.toppings.indexOf("Cheese") >= 0) {
this.pizzaPrice += 3;
}
if (this.toppings.indexOf("Peanut Butter") >= 0) {
this.pizzaPrice += 10;
}
if (this.toppings.indexOf("Vegetarian") >= 0) {
this.pizzaPrice += 2;
}
if (this.toppings.indexOf("Supreme") >= 0) {
this.pizzaPrice += 4;
}
if (this.toppings.indexOf("Pepperoni") >= 0) {
this.pizzaPrice += 3;
}
return this.pizzaPrice;
}
$(document).ready(function(){
$("form#pizza").submit(function(event){
event.preventDefault();
var size = $("input[type=radio][name=size]:checked").val();
var toppings = [];
$("input[type=checkbox][name=toppings]:checked").each(function(){
toppings.push($(this).val());
});
var newPizza = new Pizza(size,toppings,pizzaPrice);
newPizza.price();
$("#responses").append("<li>" + "You ordered a " + newPizza.size + " " + newPizza.toppings + " pizza. " + " Your total price is " + newPizza.pizzaPrice + "</li>");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Pizza Pizza</title>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.2.0.js"></script>
<script src="js/scripts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>Pizza Toppings</h2>
</div>
<form id="pizza">
<div class="form-group">
<p>What size would you like your pizza:</p>
<input type="radio" name="size" value="Small">Small.<br>
<input type="radio" name="size" value="Medium">Medium.<br>
<input type="radio" name="size" value="Large">Large.<br>
</div>
<div class="form-group">
<p>Which toppings would you like</p>
<input type="checkbox" name="toppings" value="Cheese">Cheese.<br>
<input type="checkbox" name="toppings" value="Vegetarian">Vegetarian.<br>
<input type="checkbox" name="toppings" value="Supreme">Supreme.<br>
<input type="checkbox" name="toppings" value="Pepperoni">Pepperoni.<br>
<input type="checkbox" name="toppings" value="Fruit">Fruit.<br>
<input type="checkbox" name="toppings" value="Bacon">Bacon.<br>
<input type="checkbox" name="toppings" value="Artichoke">Artichoke.<br>
<input type="checkbox" name="toppings" value="Peanut Butter">Peanut butter.<br>
</div>
<button type="submit">Let's get your order</button>
</form>
<ul id="responses">
</ul>
</div>
</body>
</html>
The statement here
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
is incorrect. As it is returning you the value of first checked checkbox.
Instead use following statement to get an array of checked values.
var toppings = $("input[type=checkbox][name=toppings]:checked").get();
Now while retrieving the values you can use the following:
(this.toppings.indexOf("Cheese") >= 0)
The indexOf() returns -1 if no matching results is found.
Hope this solves your problem.
There are a number of issues -
1.) When you do
var toppings = $("input[type=checkbox][name=toppings]:checked").val();
you already lost all the toppings except the first one. Instead you could use
var toppings = $("input[type=checkbox][name=toppings]:checked");
var i = 0;
var toppingVal;
while(i < toppings.length){
toppingVal += " "+(toppings[i]).value;
i++;
}
2.) When you are calculating the price, you make use of if..else..if blocks. How can you add up multiple toppings, only one block would execute. use only if
3.) As per my suggestion you would get a string of toppings seperated by a space(' '). So you cannot be using === for comparison. Use indexOf to find if the toppings string contains a specific topping.
Take a look at this fiddle
https://jsfiddle.net/8u67x4nm/1/ . Works fine.

Javascript to jquery conversion

I'm trying to convert this javascript DOM into jquery, and my code isn't running for some reason. This is the DOM I am using.
document.getElementById("forma").onsubmit = function () {
var ime = document.getElementById("ime").value;
var priimek = document.getElementById("priimek").value;
var stranka = document.getElementById("stranka").value;
try {
var kandidat = Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
document.getElementById("seznam").innerHTML = OblikujIzpis(PridobiPolje());
document.getElementById("obvestila").innerHTML = "Uspešen Vnos!";
document.getElementById("obvestila").className = "bg-success";
}
catch (napaka) {
document.getElementById("obvestila").innerHTML = napaka.message;
document.getElementById("obvestila").className = "bg-danger";
}
document.getElementById("forma").reset();
}
document.getElementById("forma_isci").onsubmit = function () {
var iskani_niz = document.getElementById("iskalniNiz").value;
document.getElementById("seznam").innerHTML = OblikujIzpis(Isci(iskani_niz));
document.getElementById("obvestila").innerHTML = "Rezultat iskanja po iskalnem nizu " + iskani_niz;
document.getElementById("obvestila").className = "bg-info";
}
document.getElementById("pobrisi").onclick = function () {
IzbrisiPolje();
document.getElementById("obvestila").innerHTML = "Polje je bilo izbrisano!";
document.getElementById("obvestila").className = "bg-success";
document.getElementById("seznam").innerHTML = "";
document.getElementById("forma").reset();
}
This is what I tried writing in jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("forma").submit(function(){
var ime=$("ime").val();
var priimek=$("priimek").val();
var stranka=$("stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("seznam").html(OblikujIzpis(PridobiPolje());
$("obvestila").html("Uspešen Vnos!");
$("obvestila").addClass("bg-success");
}
catch(napaka){
$("obvestila").html(napaka.message);
$("obvestila").addClass("bg-danger");
}
$("forma").reset();
$("forma_isci").submit=function(){
var iskani_niz=$("iskaniNiz").val();
$("seznam").html(OblikujIzpis(iskani_niz));
$("obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("obvestila").addClass("bg-info");
}
$("pobrisi".click=function(){
IzbrisiPolje();
$("obvestila").html("Polje je bilo izbrisano!");
$("obvestila").addClass("bg-success");
$("seznam").html("");
$("forma").reset();
}
}
});
});
</script>
here is my HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="funkcije.js"></script>
<script src="dom.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>JavaScript - DOM</title>
</head>
<body>
<div class="container">
<h1>Seznam predsedniških kandidatov!</h1>
<form action="#" id="forma_isci" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="iskalniNiz" placeholder="Iskalni niz">
</div>
<button type="submit" class="btn btn-info">Išči</button>
</form>
<br />
<br />
<h3>Vnos novih kandidatov</h3>
<form action="#" id="forma" class="form-group">
<table class="table">
<tr>
<td>Ime:</td>
<td>
<input type="text" id="ime" placeholder="Ime kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Priimek:</td>
<td>
<input type="text" id="priimek" placeholder="Priimek kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Stranka:</td>
<td>
<select id="stranka" class="form-control" >
<option>Demokratska</option>
<option>Republikanska</option>
<option>Neodvisna</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Dodaj" class="btn btn-info" />
</td>
<td>
<input type="reset" value="Ponastavi" class="btn btn-info" />
</td>
</tr>
</table>
</form>
<br />
<br />
<p id="obvestila"></p>
<br />
<br />
<h3>Seznam obstoječih kandidatov</h3>
<ul id="seznam" class="list"></ul>
<button class="btn" id="pobrisi">Pobriši seznam</button>
</div>
</body>
</html>
So anyway, I'm not going to post the functions here since they're not needed to be seen here.
The javascript code works, the site works then and the elements get added normally. But I would like to have the same effect but written in Jquery. I think some of the issues are in .className, which I replaced with .Addclass from jquery and .innerHTML where I write .html(function). If someone could convert this for me it would be great, since I am kinda new to jquery I'm having some issues.
update n1*
changed the Jquery to this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$(document).ready(function(){
$("#forma").submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").myClass("bg-success");
}
catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").myClass("bg-danger");
}
$("#forma").reset();
}
$("#forma_isci").submit=function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").myClass("bg-info");
}
$("#pobrisi".click=function(){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").myClass("bg-success");
$("#seznam").html("");
$("#forma").reset();
}
}
});
});
</script>
Added the # where there's an ID, and changed .addClass to .myClass. Add function is still not working. But some other functions are working.
The functions.
var polje = [];
function Kandidat(ime, priimek, stranka) {
if (ime ==="" || priimek === "") {
throw new Error("Podatki niso popolni!");
}
else {
var id = polje.length + 1;
var oseba = {id:id, ime:ime, priimek:priimek, stranka:stranka};
oseba.Izpis = function () {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka;
}
return oseba;
}
}
function DodajKandidataNaPolje(kandidat) {
polje.push(kandidat);
return true;
}
function PridobiPolje() {
return polje;
}
function OblikujIzpis(polje) {
var izpis = "";
for (var i = 0; i < polje.length; i++) {
izpis = izpis + "<li>" + polje[i].Izpis() + "</li>";
}
return izpis;
}
function Isci(iskalniNiz) {
var rezultat = [];
var oseba;
var vsebuje;
for (var i = 0; i < polje.length; i++) {
oseba = polje[i];
vsebuje = oseba.ime.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.priimek.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.stranka.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
}
}
}
return rezultat;
}
function IzbrisiPolje() {
polje = [];
return true;
}
in jQuery, in order to access an element, you need to use a selector. In your case, the form has an id of forma (which in jQuery selectors, you prefix it with #). In order to access your form, you need to do the following:
change this:
$("forma").submit(function(){
to this:
$("#forma").submit(function(){
Anywhere else you use jQuery to access an element in your code would have to be changed as well. use #myid for ids, .myclass for classes. See this for more information.
Here is your code (jQuery section only) with some things fixed:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var forma = $('#forma');
forma.submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").addClass("bg-success");
} catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").addClass("bg-danger");
}
forma[0].reset();
});
$("#forma_isci").submit(function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").addClass("bg-info");
});
$("#pobrisi").click(function( ){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").addClass("bg-success");
$("#seznam").html("");
forma[0].reset();
});
});
</script>

addEventListener in javascript

<html>
<head>
<script type="text/javascript">
function exe()
{
document.getElementById("cal").addEventListener("click", checkNumber,false);//after the load event,it call this function to register button event
}
function checkNumber()
{enter code here
var number1 = parseInt(document.getElementById("number"));
var number2 = document.getElementById("textbox");
var isPrime = true;
if (isNaN(number1))
number2.value = (number1 + " is not a valid number! Try again!");
else{
if (number1 == 1)
number2.value = (number1 + " is not prime!");
else{
for (var i=2; i<number1; i++){
if (number1 % i == 0){
strong text number2.value = (number2 + " is not prime. It is divisible by " + i + ".");
isPrime = false;
break;
}
}
if (isPrime)
number2.value = (number1 + " is prime!");
}
}
window.addEventListener("load",exe,false);//the first load of the page will execute this function and call function exe()
</script>
</head>
<body>
<form action="#" id="form1">
<h1 align="center">prime number calculator</h1><br>
<input align="center" type="text" size="" name="number" id="number"/><br>
<input type="button" name="cal" id="cal" value="Calculate" />
</form>
<section>
<input align="center" type="text" size="" name="num2" id="textbox"/>
</section>
</body>
</html>
I have studied javascript before this but the method I use is onclick or onload, I've never used addEventListener before, my code didn't function at all. First, when the page loads, I register an event to trigger the other function and register an event for the button, after that I call the other function for further calculation but it wouldn't work at all. I don't know which lines of codes are inappropriate, this condition must use addEventListener.
There are a few mistakes in your code. Here is the corrected version
<html>
<head>
<script ="text/javascript">
function exe()
{
document.getElementById("cal").addEventListener("click", checkNumber,false);//after the load event,it call this function to register button event
}
function checkNumber()
{
var number1 = parseInt(document.getElementById("number").value);
var number2 = document.getElementById("textbox");
var isPrime = true;
if (isNaN(number1))
number2.value = (number1 + " is not a valid number! Try again!");
else{
if (number1 == 1)
number2.value = (number1 + " is not prime!");
else{
for (var i=2; i<number1; i++){
if (number1 % i == 0){
number2.value = (number1 + " is not prime. It is divisible by " + i + ".");
isPrime = false;
break;
}
}
if (isPrime)
number2.value = (number1 + " is prime!");
}
}
}
window.addEventListener("load",exe,false);//the first load of the page will execute this function and call function exe()
</script>
</head>
<body>
<form action="#" id="form1">
<h1 align="center">prime number calculator</h1><br>
<input align="center" type="text" size="" name="number" id="number"/><br>
<input type="button" name="cal" id="cal" value="Calculate" />
</form>
<section>
<input align="center" type="text" size="" name="num2" id="textbox"/>
</section>
</body>

Trying to display problems one at a time.

I am trying to make an simple math test that has 10 problems. They have to display one at a time. I have hit a roadblock and I'm not sure how to move forward from here. I made a submit button and I figured I could just load the next question onClick load but it's a little more complicated than I thought.Any advice would be greatly appreciated.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive Math Worksheet</title>
<script type="text/javascript">
var mathProblem = new Array();
var carryOver = document.getElementById("carry");
var correct = 0;
var wrong = 2;
// writing the problem 10 times
function writeProblem(){
for (var i=1; i<11; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
document.getElementById("top"+i).innerHTML = num1;
document.getElementById("bottom"+i).innerHTML = "+" + num2;
mathProblem[i] = num1 + num2;
document.forms["problem"+i]["answer"+i].value = "";
}
}
function submitAnswer(){
var i=0;
for (i=1;i<11;x++) {
if (document.forms["problem"+i]["answer"+i].value == mathProblem[i]) {
return true;
}
else if(isNaN (document.forms["problem"+i]["answer"+i].value)){
alert("This is not a spelling test please use numbers");
return false;
}
}
}
</script>
</head>
<body onload="writeProblem()">
<h2>Practicing Your Pluses!</h2>
<form name="problem1">
<input type="text" size="1" name="carry1"><br/>
<label id="top1"></label><br />
<label id="bottom1"></label><br /><hr width="60px" align="left"/>
<input type="text" size="3" name="answer1">
</form><br/>
<input type="button" onClick="submitAnswer()" value="Submit Answers"/>
</body>
</html>
I think This above code gives this Error
Uncaught TypeError: Cannot set property 'innerHTML' of null
Because in your code writeProblem() function has mistake, by the time the function call document read only the element with id "top1" another ids are not there but you are repeting the loop 11 times, so change the onload function body according to the standards of Javascript
I have updated the code please check once JS Fiddle
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive Math Worksheet</title>
<script type="text/javascript">
var mathProblem = new Array();
var carryOver = document.getElementById("carry");
var correct = 0;
var wrong = 2;
// writing the problem 10 times
function writeProblem(){
for (var i=1; i<11; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
document.getElementById("top").innerHTML = num1;
document.getElementById("bottom").innerHTML = "+" + num2;
mathProblem[i] = num1 + num2;
document.forms["problem"]["answer"].value = "";
}
}
function submitAnswer(){
var i=0;
for (i=1;i<11;i++) {
if (document.forms["problem"]["answer"].value == mathProblem[i]) {
writeProblem();
return true;
}
else if(isNaN (document.forms["problem"]["answer"].value)){
alert("This is not a spelling test please use numbers");
return false;
}
}
}
</script>
</head>
<body onload="writeProblem()">
<h2>Practicing Your Pluses!</h2>
<form name="problem">
<input type="text" size="1" name="carry1"><br/>
<label id="top"></label><br />
<label id="bottom"></label><br /><hr width="60px" align="left"/>
<input type="text" size="3" name="answer">
</form><br/>
<input type="button" onClick="submitAnswer()" value="Submit Answers"/>
</body>
</html>
SOLUTION
Avoid using onload, onclick or any inline event or style (read more)
NOTE: In this solution I'm using classList that aint fully supported.
HTML
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<div>
<label class="top"></label><br />
<label class="bottom"></label><br />
<hr />
<input class="answer" type="text">
</div>
<input id="submit" type="button" value="Submit"/>
CSS
div, input {
width: 60px;
}
label {
float: right;
padding-right: 10px;
}
.invalid {
border: 1px solid red;
}
JS
var mathProblem = [];
var tops = document.getElementsByClassName('top');
var bottoms = document.getElementsByClassName('bottom');
var answers = document.getElementsByClassName('answer');
function writeProblem(){
for (var i=0; i<3; i++){
num1 = (Math.floor(Math.random()*50)+1);
num2 = (Math.floor(Math.random()*50)+1);
tops[i].innerHTML = num1;
bottoms[i].innerHTML = '+' + num2;
mathProblem[i] = num1 + num2;
}
}
window.addEventListener('load', writeProblem);
function submitAnswer(){
var invalid = document.getElementsByClassName('invalid');
for(var i=0; i<invalid.length; i++){
invalid[i].classList.remove('invalid');
}
var correct = 0;
var wrong = 0;
for (var a=0; a<3; a++) {
var answer = answers[a];
if(isNaN(Number(answer.value))){
answer.classList.add('invalid');
alert('This is not a spelling test, please use numbers');
return false;
}
if(answer.value === ''){
answer.classList.add('invalid');
alert('Answer all questions please');
return false;
}
if (Number(answer.value) === mathProblem[a]) {
correct++;
}
else {
answer.classList.add('invalid');
wrong++;
}
}
alert('Correct: ' + correct + '\nWrong: ' + wrong);
}
document.getElementById('submit')
.addEventListener('click', submitAnswer);

Categories