Plexxl
Plexxl

Reputation: 85

Get Multiple JavaScript Variables from 1 HTML Input

I'm looking for a way I can get multiple JavaScript Variables (for my code, 4 inputs) from one HTML input (in this case, a text input) so that when anyone hits submit multiple times, it will put each click into a different variable.

<form name="mathGuesser" id="mathGuesser" class="mathGuesser">
    <h3>y - 5 = 2(x - 4)</h3>
    <input type="text" name="mGuesser" placeholder="Enter the answer in slope-intercept form"></input>
    <button type="button" onclick="mathCheck()">Check</button>
    <script language="javascript">
        function mathCheck() {
            var inputValues1 = document.mathGuesser.mGuesser.value;
        }
    </script>
</form>

Upvotes: 0

Views: 1123

Answers (2)

Obsidian Age
Obsidian Age

Reputation: 42304

What you want to do is set all four of your variables outside of your function. Then inside of your function grab the value from the input field, and check whether the values have been set or not. This can be done by checking their typeof is not undefined. If they're defined, skip on to the nxt value using an else if.

This can be seen in the following:

var value1, value2, value3, value4;

document.getElementsByTagName('button')[0].addEventListener('click', function() {
  var field = document.getElementsByTagName('input')[0].value;

  if (typeof value1 == 'undefined') {
    value1 = field;
  } else if (typeof value2 == 'undefined') {
    value2 = field;
  } else if (typeof value3 == 'undefined') {
    value3 = field;
  } else if (typeof value4 == 'undefined') {
    value4 = field;
  }

  console.log(value1, value2, value3, value4);
});
<input type="text" name="mGuesser" placeholder="Enter the answer in slope-intercept form">
<button type="button">Check</button>

Upvotes: 0

John R
John R

Reputation: 1508

Use an array

values = []
onclickfunction(value){
    values.push(value)
}

Upvotes: 2

Related Questions