2

I want to use the values in the array userInfo as parameters in the getBMR function. How do I do that?

function userInput() {
  var gender = document.querySelector('input[name="gender"]:checked').value;
  var length = document.getElementById('length').value;
  var weight = document.getElementById('weight').value;
  var age = document.getElementById('age').value;
  
  if (length || weight || age === (strValue)) {
    length = parseInt(length);
    weight = parseInt(weight);
    age = parseInt(age);
    var userInfo = [gender, length, weight, age];
    return userInfo;
  }
}

function getBMR(gender, length, weight, age) {
// ...
}

Been googling like crazy but I can't seem to find the solution. Using the console.log after the array declaration I can clearly see that the array stores the data. My problem is getting this data outside the function.

Here's my HTML:

<html>

<head>
</head>

<body>

  <form action="">
    <input type="radio" name="gender" id="gender" value="male" checked="checked">Man<br>
    <input type="radio" name="gender" id="gender" value="female">Kvinna<br>

    <label>Längd</label>
    <input type="number" id="length"></input>

    <label>Vikt</label>
    <input type="number" id="weight"></input>

    <label>Ålder</label>
    <input type="number" id="age"></input>

    <button onclick="userInput()">Hämta BMR</button>
  </form>
  <p id="dittBMR"></p>
</body>

</html>

Really appreciating all the help that I can get!

Thanks!

  • Please have a look at the answers given here: http://stackoverflow.com/questions/19570629/pass-all-the-values-from-an-array-into-a-function-as-parameters – Nicole Oct 25 '16 at 06:15

2 Answers2

0

If your parameters are consistent and the list doesn't need to be dynamic you should be able to do:

function getBMR(userInput()[0], userInput()[1], userInput()[2], userInput()[3]) {
// ...
}
btburton42
  • 3,307
  • 2
  • 13
  • 10
0

The problem is that when you have a var declared, its scope is only until the function finishes execution. So, i think a better way of doing this is to have separate functions for the parameters you need. Something like:

function getLenght() {
     return document.getElementById('length').value;
} 

So whenever you call getBMR you would first declare and assign the other variables like so:

var length = getLength() ;
getBMR(length,...) ;

And also, an even better way would be to use jQuery where you can do:

$. ("#length").val();

And this will return the value of the input.

Hope this helps.

MZokov
  • 316
  • 1
  • 3
  • 11