0

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>
1
  • @ObsidianAge I am trying to get multiple inputs from one text input so that when anyone hits submit, they get their inputs divided up. Commented Mar 11, 2018 at 23:16

2 Answers 2

2

Use an array

values = []
onclickfunction(value){
    values.push(value)
}
Sign up to request clarification or add additional context in comments.

1 Comment

How am I going to put the values into the array?
0

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>

1 Comment

Works, but seems a little unnecessary complicated compared to using an array and pushing to that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.