S. Miller S. Miller - 7 months ago 10
Javascript Question

How to read text from HTML input in JavaScript function?

On the webpage, the user is able to write text in a text field. I would like to use the button on this page to read this text and then place it somewhere else. Here is the simplified markup so far:

<div id="Demo1" class="w3-accordion-content w3-container">
<h4>Let's make your Resume Header</h4>
<table>
<tr>
<th>Name</th>
<td><input type="text" id="name"></td>
</tr>
</table>
<button onclick="header()" class="save">SAVE</button>
</div>


And here is the JavaScript code that I have:

function header() {
var name = document.getElementById(name).value;
alert(name);
}


This alert does not work at all when I run it. I cannot figure out why, any help is much appreciated.

Answer

You have missed quotes. So use document.getElementById('name').value instead of document.getElementById(name).value.

if you use name as a parameter then you can use it without quotes.

function header() {
  var name = document.getElementById('name').value;
  alert(name);
}
<div id="Demo1" class="w3-accordion-content w3-container">
  <h4>Let's make your Resume Header</h4>
  <table>
    <tr>
      <th>Name</th>
      <td>
        <input type="text" id="name">
      </td>
    </tr>
  </table>
  <button onclick="header()" class="save">SAVE</button>
</div>

Comments