+ 1

Defining Javascript Function

Ive been given a piece of Javascript code to edit for taking inputs from a HTML form with 2 different inputs and outputting the sum of the two inputs to the "alert" that pops up on the screen (i made the form as part of the course). The task is a 5 part question and Im stuck on one part which asks you to define the calc() function which you will see in the code below. I think ive got the bits of HTML for the form all in order, but how to define the calc() function is really confusing me. I understand the syntax for defining a function, but I cant for the life of me figure what to put, or even where to put it in this example?! Here is the code: window.onload = function() { let btn = document.getElementById("buyBtn"); btn.onclick = function() { let adults = document.getElementById("adults").value; let children = document.getElementById("children").value; let price = calc(adults, children); alert(price); } } Any help or advice much appreciated. I've spent 3 evenings Googling and guessing and going back through notes and trying different things and I'm fed up now :(

28th Mar 2022, 9:54 PM
Thomas Murphy
4 Answers
+ 1
But what the calc( ) function was supposed to do?
28th Mar 2022, 10:09 PM
Ipang
+ 2
Sorry, the calc function is supposed to add together the values of "children" and "adults" which are the form labels for 2 different inputs
28th Mar 2022, 10:13 PM
Thomas Murphy
+ 2
28th Mar 2022, 11:38 PM
SoloProg
SoloProg - avatar
+ 1
If this means calculating different price of something (ticket for example), then calc( ) must also know each category's price. Making up the prices, this might do. Add it somewhere before the calc( ) invocation ... const calc = ( adults, children ) => { adults = Number( adults ); children = Number( children ); if( isNaN( adults ) || isNaN( children ) ) { return 0; } const adultPrice = 10, childrenPrice = 5; // dummies return adults * adultPrice + children * childrenPrice; }
28th Mar 2022, 10:26 PM
Ipang