Tom Bom
Tom Bom

Reputation: 1721

Showing form input on submit

I have a form with one input field and when I press enter I would like to see this input written under the form. I would like to have as many inputs as possible, each new one to be displayed under the previous one.

I tried it like this but I failed.

<form>
  <input type="text" name="" value="" id="form-input">
</form>
<ul>
  <li id="form-list"></li>
</ul>

And then inside my <script> tag:

var formInput = document.getElementById("form-input")
var formOutput = document.getElementById("form-list")
formOutput.innerHTML = formInput.value;
formInput.onsubmit = function() {
  formOutput.innerHTML = this.value;
}

When I press enter it refreshes the page, if I change onsubmit to oninput it displays what I'm writing but it is not saved.

Is it possible to display multiple inputs like this? Thanks

Upvotes: 1

Views: 120

Answers (3)

Fidel Orozco
Fidel Orozco

Reputation: 1056

You can make your code run with these changes in HTML and your Javascript:

var formInput = document.getElementById("form-input")
var formOutput = document.getElementById("form-list")

function AddElement() {
  var NewValue = formInput.value;
  var li = document.createElement('li');
  var text = document.createTextNode(NewValue);
  li.appendChild(text);
  formOutput.appendChild(li);
  return false;
}
<form onsubmit="return AddElement();">
  <input type="text" name="" value="" id="form-input">
</form>
<ul id="form-list"></ul>

Upvotes: 0

Chirag Ravindra
Chirag Ravindra

Reputation: 4830

I'm not sure if I understood your question correctly but here is one way to listen for the 'enter' key press on an input element and create a dynamic list of input elements with the entered value.

var inputEl = document.getElementById("in");
var targetList = document.getElementById("list");

function createItem(text){
  var listItem = document.createElement('li');
  var input  = document.createElement('input');
  input.type = 'text';
  input.value = text;
  listItem.appendChild(input);
  targetList.appendChild(listItem);
}

inputEl.addEventListener('keydown', function(e) {
  if (e.keyCode == 13) {
    createItem(inputEl.value);
    inputEl.value = '';
    e.preventDefault();
    return false;
  }
})
<form>
  <input id="in" type="text" name="" value="">
</form>
<ul id="list">
</ul>

Upvotes: 2

Netorica
Netorica

Reputation: 19337

When I press enter it refreshes the page, if I change onsubmit to oninput it displays what I'm writing but it is not saved.

You can use cookies to store and persist data on every refresh

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

or WebStorage/Application Storage

https://www.w3schools.com/html/html5_webstorage.asp

But I really advise that learn to use server-side scripting with a database so your data will have permanent persistence across browser sessions

https://www.w3schools.com/php/default.asp

Upvotes: 1

Related Questions