0

I'm trying to create a calculator that takes a number as input, decides in which range this number is, and adds a corresponding price to the basic price (currently set to 0). However, I'm stuck at a rather simple for-loop I inserted to iterate over the ranges (in seizprijs). Without the for-loop, the code appears to do just fine. However, if I run the code including the for-loop, the function returns 'not defined'.

I'm completely new to coding, so I expect it to be a simple issue. However, I tried every suggestion I could find online, and nothing seems to work.

const seizprijs = [
{tijd : "winter", bdatum : 1, edatum : 5, prijs : 45},
{tijd: "lente", bdatum: 5, edatum: 9, prijs: 50}
];

function myFunction() {
  var prijs = 0;

  var vdat = document.getElementById("datum");
  var vdatum = vdat.value;

  for (var x = 0, x < seizprijs.length, x++){

    if (vdatum > seizprijs[1].bdatum && vdatum < seizprijs[1].edatum)
    {
      prijs += seizprijs[1].prijs;
    }
  }

 document.getElementById("demo").innerHTML = "Totaalprijs:" + prijs;

}
<h1>Boeking</h1>
<p id="demo">Totaalprijs: </p>
<form id="boeking">
  <input type="number" name="datum" id="datum">
</form>
<button type="button" onclick="myFunction()">Prijs berekenen</button>

1

2 Answers 2

1

you are using , instead of ; in your for loop

try like this

for (var x = 0; x < seizprijs.length; x++)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was it! I changed that around before, but apparently made another mistake at first, and didn't change it back. It works now! :)
0

The problem seems to be the data type of the value from the input. Use + unary operator to convert the string to number. Also if you are iterating a loop use the index , x in your code to access the value from the array of object

const seizprijs = [{
    tijd: "winter",
    bdatum: 1,
    edatum: 5,
    prijs: 45
  },
  {
    tijd: "lente",
    bdatum: 5,
    edatum: 9,
    prijs: 50
  }
];

function myFunction() {
  var prijs = 0;

  var vdat = document.getElementById("datum");
  var vdatum = +vdat.value;

  for (var x = 0; x < seizprijs.length; x++) {

    if (vdatum > seizprijs[x].bdatum && vdatum < seizprijs[x].edatum) {
      prijs += seizprijs[x].prijs;
    }
  }

  document.getElementById("demo").innerHTML = "Totaalprijs:" + prijs;

}
<h1>Boeking</h1>
<p id="demo">Totaalprijs: </p>
<form id="boeking">
  <input type="number" name="datum" id="datum">
</form>
<button type="button" onclick="myFunction()">Prijs berekenen</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.