0

So i'm working on a side project, a HTML game. The user has 3 buttons to choose from, when they click one it sets an input fields value to that number

I am having trouble with the validation portion of it. I'm very new to javascript so please don't laugh if its a very stupid problem XD.

I've started writing a function it is posted below

function Check() {
    var UserInput1 = document.forms["calculator"]["userInput1"];
    var UserInput2 = document.forms["calculator"]["userInput2"];

    var result;

    function Sum(Uval1, Uval2) {
        return Uval1 + Uval2;
    }

    var result = Sum(UserInput1, UserInput2);

    console.log('User Input 1 = ', UserInput1);
    console.log('User Input 2 = ', UserInput2);
    console.log('Result = ', result);
}

I want the function to add the 2 user inputs and validate that they are equal to another preset variable in my JS file

imjared
  • 19,492
  • 4
  • 49
  • 72
TD3
  • 1
  • 2
  • 1
    The form control values are strings, so the `+` operator works as concatenation, not addition so you'll get, say, "11" rather than `2`. See [* Addition is not working in JavaScript*](https://stackoverflow.com/questions/8377410/addition-is-not-working-in-javascript). – RobG Jul 16 '19 at 20:33
  • @RobG So how would I add the 2 values from the form fields? – TD3 Jul 16 '19 at 20:35
  • Coerce them to number, e.g. `return +Uval1 + +Uval2` or `return Number(Uval1) + Number(Uval2)`. I've suggested a duplicate (now). :-) – RobG Jul 16 '19 at 20:36
  • @RobG This is what I keep getting in my Chrome Console "Result = [object HTMLInputElement][object HTMLInputElement]" – TD3 Jul 16 '19 at 20:37
  • Oh, sorry! You need to get the value of the inputs: `console.log('User Input 1 = ', UserInput1.value)`. – RobG Jul 16 '19 at 20:38
  • document.forms["calculator"]["userInput1"].value – A. Meshu Jul 16 '19 at 20:39
  • ``` function Check() { var UserInput1 = document.forms["calculator"]["userInput1"].value; var UserInput2 = document.forms["calculator"]["userInput2"].value; var result; function Sum() { return UserInput1 + UserInput2; } } eval("result = Sum(UserInput1, UserInput2);"); `` Okay so I wrote this but I'm a bit confused on what's wrong with this function – TD3 Jul 16 '19 at 20:46

0 Answers0