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>
An
inputelement does not have any descendants, so.innerHTMLreturns an empty string. If you want to get the value, you have to access the.valueproperty (for more info, see theHTMLInputElementdocumentation 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:
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.