user2558935
user2558935

Reputation: 9

How to send information from HTML <input> element to <span> using JavaScript .innerHTML?

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>

Upvotes: 0

Views: 1200

Answers (3)

Super Hornet
Super Hornet

Reputation: 2907

you should do this first:

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

Upvotes: 0

Harry
Harry

Reputation: 89760

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;

Upvotes: 1

DevlshOne
DevlshOne

Reputation: 8457

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?

Upvotes: 1

Related Questions