0

Good afternoon guys,

I received an assignment from my school. The task is not that hard, but due the lack of explanation from my teacher, I am very stuck.

The assignment is:

You create an input field. In the input field you write 3 numbers. For example 2, 3, 5. The numbers are split by the ','.

Then you have a select, with the values - , +, / and *. So if you select + and then click the button calculate, it will do 2 + 3 + 5 and then show the answer.

This is my code right now.

<body>
    <h1>Calculate</h1><br>
    Numbers: <input type="text" name="fill" id="fill"><br><br>
    Operation:
    <select name="select" id="select">
      <option value="plus">+</option>
      <option value="min">-</option>
      <option value="keer">*</option>
      <option value="delen">/</option>
    </select><br><br>
    <button onclick="count()">Count</button>

    <div class="answer"></div>

    <script>
        function count(){
            var operator = document.getElementById("select").value;
            var string = document.getElementById("fill").value;
            var array = string.split(",");

        }
    </script>

So it reads what's inside the input, it reads what I selected in the select and it knows that I need to split the input with ','.

I am stuck now. Can someone give me a hand?

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
WesleytJ
  • 31
  • 10
  • 2
    Now You need `switch (operator) { case 'plus': ...; case 'min': ... etc. }`. In every case there would be something like `var result = array[0]; for (var i = 1; i < array.length; i++) result += array[i];`. – Roman Hocke Jun 09 '17 at 10:26
  • @RomanHocke That is indeed correct - why not post that as the answer since it shows the OP where to go next. – Kallum Tanton Jun 09 '17 at 10:27
  • It sounds like a pretty clear explanation. You already split the string, so now you got an array of three numbers (or actually three strings containing numeric characters, which could require some conversion first). As a next step, I'd first try to simply add up all the numbers in `array`. When that works, you can write conditions (using `if` or `switch`) to implement the other operators. The basis implementation of those will be the same as for add, just with other operators. Just tackle the different parts one at a time. – GolezTrol Jun 09 '17 at 10:29
  • There's some good information been handed out thus far - if you're still struggling then head over to the Mozilla Developer Network to research some of the points provided: https://developer.mozilla.org – Kallum Tanton Jun 09 '17 at 10:40

3 Answers3

0

Are you allowed to ask for that in SO? :-)

Well, since this is a school exercise, I'll give you some clues:

array contains all the operands ["2", "3", "5"].

Create a variable that will contain the results and initialize it with the first value in the array (array[0]). Be careful, now it contains a string and "2"+"3" is "23" you'll have to parse the value and convert it to Int or Float (look at parseInt method).

Iterate the array starting from the second element (array[1]), depending on the "operator" value, then you'll have to do *=, +=, /=, -= on the result variable for each element in the array but the first one.

After the iteration you'll have the result inside the variable.

I am assuming you are not allowed to use eval function (eval is evil :-))

I hope it helps.

marcm
  • 171
  • 9
0

Here is a plunker with some step to follow : https://plnkr.co/edit/yjgZ5uCM33eoRMzwX0ZL?p=preview

Steps:

  1. Check the validity of your input
  2. Identify the selected Operator
  3. Loop over your number array and operate your elements two by two.
  4. Add your results to your DOM

Preview on how to add the results to your DOM

  // Add the results to your DOM
  var para = document.createElement("p");
  var node = document.createTextNode(results.toString());
  para.appendChild(node);
  var element = document.getElementById("answer");
  element.appendChild(para);

I won't go any further as this is a school exercise. But i think these informations will allow you to better understand the structure and the logical interests behind this exercise.

Good luck.

Louis Lecocq
  • 1,764
  • 3
  • 17
  • 38
  • Please remove the code block from the steps and add in two code blocks from the plunker - one with the HTML, the other with JS. – Kallum Tanton Jun 09 '17 at 10:38
0
  1. Create a var and assign an array from your input to it. Google "javascript array from string" but you already know that you have to use .split().

  2. Create second var for your answer.

  3. Detect which operand you have to use: Retrieving the text of the selected <option> in <select> element

  4. Now, the easiest way is to use switch statement, case all operands and do not forget break;

  5. Now you just have to do the math with every element from your array. You can use a basic for loop (total += i or total *= i) etc. Alternatively you could use .reduce() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=control

  6. Set an answer var to a answer's div

Thats all you really need to complete this task.

I made an example solution but do not copy paste it, really. Try to write your own solution, you will learn a lot by doing it on your own.

function count() {
   var arr = document.getElementById('fill').value.split(",");
   var operations = {
     '+' : arr.reduce((a, b) => parseFloat(a) + parseFloat(b)),
     '-' : arr.reduce((a, b) => parseFloat(a) - parseFloat(b)),
     '*' : arr.reduce((a, b) => parseFloat(a) * parseFloat(b)),
     '/' : arr.reduce((a, b) => parseFloat(a) / parseFloat(b))
   }
   var answer = operations[document.getElementById('select').selectedOptions[0].text];
  
   document.getElementById('answer').innerHTML = answer;
}
<h1>Calculate</h1><br>
    Numbers: <input type="text" value="1,2,5" name="fill" id="fill"><br><br>
    Operation:
    <select name="select" id="select">
      <option value="plus">+</option>
      <option value="min">-</option>
      <option value="keer">*</option>
      <option value="delen">/</option>
    </select><br><br>
    <button onclick="count()">Count</button>

    <div id="answer"></div>