Skip to content

Instantly share code, notes, and snippets.

@aresnick
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aresnick/492eeadef02b9ce02632 to your computer and use it in GitHub Desktop.
Save aresnick/492eeadef02b9ce02632 to your computer and use it in GitHub Desktop.

A simple example of taking text input from a user

A barebones example of taking text input from a user and programmatically using it elsewhere in your page/project.


Further doing

Modify the code so that:

  • …the submission is only added if it contains only letters and whitespace (i.e. it should either throw an error message—or just do nothing—if I enter a 1).
  • …the submission is not just added to the DOM, but to localStorage
  • …when a user visits the page again after having submitted something in the past, they see their old submissions there (again, via localStorage)

Further reading

<html>
<body>
<input type='text'></input> <!-- set up a simple text input -->
<input type='submit'></input> <!-- and a button to submit that input -->
<ul>
</ul>
<script>
var text = document.querySelector("input[type='text']"); // grab our text input
var submit = document.querySelector("input[type='submit']"); // and our submit button
var addChoice = function(choice, list) { // a small function for adding a choice that we submit to our list
var li = document.createElement('li');
li.innerHTML = choice;
list.appendChild(li);
};
submit.addEventListener('click', function() { // when our submit is clicked
var myUl = document.querySelector('ul'); // grab our list
addChoice(text.value, myUl); // and the text input's text to it as a new list element
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment