0

I have an input for in my HTML code, and I want to capture the input as a variable in javascript.

HTML:

<form id="answer">
      Answer: <input type="text" answer="response"><br>
      <input type="button" value="Submit" onclick="answerInput()"> <br><br>
    </form>

Javascript:

var answer = document.getElementById('answer').value;

I would expect this to return the value of what was put in the field before submit was hit, but it returns undefined. I need someone to be able to put in a value (in this case a number) and have that number be available as a variable.

Thank you for being patient, I'm new to all this and teaching myself.

ellipsis
  • 12,049
  • 2
  • 17
  • 33
Domo Dan
  • 167
  • 1
  • 1
  • 5

2 Answers2

2

Put the id answer on the input tag not on the form tag

function answerInput()
{
var answer = document.getElementById('answer').value;
console.log(answer)}
<form>
      Answer: <input type="text" id="answer" answer="response"><br>
      <input type="button" value="Submit" onclick="answerInput()"> <br><br>
    </form>
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

Your form has the id of "answer". Your input has no id. Javascript checks the element with the id of "answer" for its "value" property, but the form does not have a value property, so it returns undefined.

So you can just move id="answer" from the form tag to the input tag to get your desired result.

Cat
  • 4,141
  • 2
  • 10
  • 18