1

When the user enters text in the text field and clicks the submit button their text should come up on the screen. Right now nothing shows.

JS Bin: http://jsbin.com/itotub/1/edit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
function myOnloadFunc() {
    var inputAnswer = document.getElementById("inputAnswer");
    var userAnswer = inputAnswer.innerHTML;

    var submitButton = document.getElementById("submitButton");

    submitButton.onclick = function() {
        document.write(userAnswer);
    };
}

window.onload = myOnloadFunc;
</script>
</head>

<body>
<input type="text" id="inputAnswer" placeholder="Enter your answer">
<input type="button" id="submitButton" value=">">
</body>
</html>

1 Answer 1

4

An input element does not have any descendants, so .innerHTML returns an empty string. If you want to get the value, you have to access the .value property (for more info, see the HTMLInputElement documentation on MDN).

Another problem is that you are trying to get the value before the user actually typed in anything. You don't want to get the value on page load but when the user clicks the button:

submitButton.onclick = function() {
    console.log(inputAnswer.value);
    // or alert(inputAnswer.value);
};

I would refrain from using document.write, even if it is only for testing purposes. At least understand what happens when you call it after the DOM was loaded.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.