Magdi Gamal Magdi Gamal - 1 year ago 48
Javascript Question

Javascript - How to add form's input into the dom properly?

I'm just trying to make a simple javascript form where everytime you type and submit something, it shows up in the page.

<form id="myForm">
<input id="text" type="text" name="name" value="">
<input id="submit" type="submit">
</form>


javascript:

document.getElementById("myForm").addEventListener('submit', function(){

var input = document.getElementById("text")
var output = input.value;

var printOutput = document.createElement('h1');
printOutput.innerHTML = output;
document.body.appendChild(printOutput);

});


This shows up for a second then disappears. I understand it's happening because the dom manipulation is happening inside the submit event. But I'm not sure how to go around that.

My first instinct was to use

return output;


then reference the whole function once I appendChild from outside it. But that didn't work either. I'm guessing cause It's an Eventlistener and not a normal function... any ideas on how to go with this?

Answer Source

You are ignoring the form primordial sense that is to send data over a server.

You don't need aform for what you intend. you need only input elements and a handler on the button.

function handler (){ 

  var input = document.getElementById("text")
  var output = input.value;

  var printOutput = document.createElement('h1');
  printOutput.innerHTML = output;
  document.body.appendChild(printOutput);
   document.getElementById("text").value='';

}

document.getElementById("submit").addEventListener('click', handler);
   document.getElementById("text").addEventListener('keypress', function(e){ (e.charCode == 13) && handler();});
<div id="myForm">
  <input id="text" type="text" name="name" value="">
  <input id="submit" type="submit">
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download