John Allison
John Allison

Reputation: 367

How do I submit data from a text field in HTML to a JavaScript variable?

I cannot figure out how to pass an HTML input to a JS variable.

<form id="form" target="_self">
    <input type="text" id="task" placeholder="What's on the agenda?" onsubmit="getForm()">
</form>

My HTML form with the function being called as follows:

function getForm() {
    var form = document.getElementById("task").value;
    console.log(form);
}

However, when I press enter after typing into the input text, it just refreshes the page and changes the URL from index.html to index.html?task=foo and doesn't log anything in the console.

Upvotes: 0

Views: 1226

Answers (2)

Federico Moretti
Federico Moretti

Reputation: 584

Try this:

<form id="form" onsubmit="getForm()" target="_self">
  <input id="task" placeholder="What's on the agenda?" type="text">
</form>

and

function getForm(event) {
  event.preventDefault();
  var form = document.getElementById("task").value;
  console.log(form);
}

…but keep in mind that you need at least a button or an input to submit the form.

Upvotes: 1

benbotto
benbotto

Reputation: 2440

There are two issues with the OP's code.

  1. The getForm function will not execute because onsubmit is wired up against the input element instead of the form element. HTMLInputElement doesn't emit submit events.
  2. The default action of a form is to submit the form to the server, so even if the getForm function were correctly wired up it would execute quickly and then the page would refresh. Likely you want to prevent that default action.

Generally speaking, it's good practice to wire up event listeners in your JavaScript code. Here's a snippet that demonstrates working code akin to what the OP is attempting.

'use strict';

const taskFrm = document.getElementById('taskFrm');
const taskTxt = document.getElementById('taskTxt');

taskFrm.addEventListener('submit', e => {
  e.preventDefault();
  console.log(taskTxt.value);
});
<form id="taskFrm">
  <input id="taskTxt" placeholder="What's on the agenda?">
</form>

For the sake of completeness, if you want to wire up the onsubmit function in the HTML, here's how:

function getForm(e) {
    var form = document.getElementById("task").value;
    console.log(form);
    
    e.preventDefault(); // Or return false.
}
<form id="form" target="_self" onsubmit="getForm(event)">
    <input type="text" id="task" placeholder="What's on the agenda?">
</form>

Upvotes: 1

Related Questions