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>

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

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?

1 Comment

It's one of my favorite posts here on SO. Certainly better than any W3 tutorial. ;)
0

you should do this first:

var user= document.getElementsByName("user");
var hello = document.getElementById("hello");
 hello.innerHTML = "How are you " + user[0].value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.