I have a script that when a user enters something in the text field and then press “Enter” on their keyboard it will display what they’ve entered.
This script works perfectly in document.writeln but when I tried to convert it into innerHTML, id does NOT work and I’m not sure why
<html>
<head>
<script type="text/javascript">
function handleKeyPress(e,form){
var key=e.keyCode || e.which;
if (key==13){
Display();
}
}
function Display(){
var newtext = document.myform.inputBox.value;
document.writeln(newtext);
}
</script>
</head>
<body>
<FORM NAME="myform">
<input id="search" name="inputBox" type="text" value="" onkeypress="handleKeyPress(event,this.form)">
<input id="submit" type="button" value="Submit" onClick="Display()">
</form>
</body>
</html>
Here’s my code for innerHTML, as you can see, both codes are identical except that one uses document.writeln() and the other uses getElementById()
<html>
<head>
<script type="text/javascript">
function handleKeyPress(e,form){
var key=e.keyCode || e.which;
if (key==13){
Display();
}
}
function Display(){
var newtext = document.myform.inputBox.value;
var z=document.getElementById("info");
z.innerHTML = newtext;
}
</script>
</head>
<body>
<FORM NAME="myform">
<input id="search" name="inputBox" type="text" value="" onkeypress="handleKeyPress(event,this.form)">
<input id="submit" type="button" value="Submit" onClick="Display()">
</form>
<p id="info"></p>
</body>
</html>
Very confusing!!!