Skip to content

Instantly share code, notes, and snippets.

@Elizabella
Forked from prof3ssorSt3v3/input-to-object.html
Created July 15, 2021 01:46
Show Gist options
  • Save Elizabella/2a66fce2697dba8221e426b6dd118c9e to your computer and use it in GitHub Desktop.
Save Elizabella/2a66fce2697dba8221e426b6dd118c9e to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Putting User Input into JS Objects</title>
<style>
.formBox{
padding: 0.5rem 2rem;
}
</style>
</head>
<body>
<form>
<div class="formBox">
<label for="title">Movie</label>
<input type="text" id="title" placeholder="Title"/>
</div>
<div class="formBox">
<label for="yr">Year</label>
<input type="number" id="yr" placeholder="Year"/>
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
<script>
let movies = [];
// example {id:1592304983049, title: 'Deadpool', year: 2015}
const addMovie = (ev)=>{
ev.preventDefault(); //to stop the form submitting
let movie = {
id: Date.now(),
title: document.getElementById('title').value,
year: document.getElementById('yr').value
}
movies.push(movie);
document.forms[0].reset(); // to clear the form for the next entries
//document.querySelector('form').reset();
//for display purposes only
console.warn('added' , {movies} );
let pre = document.querySelector('#msg pre');
pre.textContent = '\n' + JSON.stringify(movies, '\t', 2);
//saving to localStorage
localStorage.setItem('MyMovieList', JSON.stringify(movies) );
}
document.addEventListener('DOMContentLoaded', ()=>{
document.getElementById('btn').addEventListener('click', addMovie);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment