0

I'm very new to JavaScript and trying to mimic an example in a book I'm reading. I would like to take what is input to a HTML element and send the data to a element using .innerHTML. I don't know what is wrong.

<!DOCTYPE html>
<html>
<head>
 <title>JS Form</title>
</head>
<body>
   <form id="date">
     <table>
      <tr><td><input type="text" name="user" placeholder="Please input name"    onchange="greeting();"></td>
      </tr>
      <tr><td><span id="hello"></span></td>
      </tr> 
     </table>
   </form>
<script type="text/javascript">
   function greeting() {
     var user = document.date.user.value;
     var hello = document.getElementById("hello");
     hello.innerHTML = "How are you " + user;
   }
</script>
</body>
</html>
Super Hornet
  • 2,839
  • 5
  • 27
  • 55
user2558935
  • 9
  • 1
  • 2

3 Answers3

1

Add name="date" to your form tag like below. Else document.date.user.value will not work.

<form id="date" name="date">

Another way to get around the issue, is accessing the date property of the window object.

window.date.user.value;

This is possible because you've set an id on the form.

Or you might consider accessing the form using its id and then get user value as follows:

var user = document.getElementById("date").user.value;
Harry
  • 87,580
  • 25
  • 202
  • 214
1

For simplification, and depending on your browser, you could use document.querySelector. Take a look at this very helpful SO post: JavaScript: how to get value of text input field?

Community
  • 1
  • 1
DevlshOne
  • 8,357
  • 1
  • 29
  • 37
0

you should do this first:

var user= document.getElementsByName("user");
var hello = document.getElementById("hello");
 hello.innerHTML = "How are you " + user[0].value;
Super Hornet
  • 2,839
  • 5
  • 27
  • 55