Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created February 4, 2019 16:16
Show Gist options
  • Select an option

  • Save prof3ssorSt3v3/52ebd432bb7b8a155985a2f82509541d to your computer and use it in GitHub Desktop.

Select an option

Save prof3ssorSt3v3/52ebd432bb7b8a155985a2f82509541d 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>
@Saraaa92

Copy link
Copy Markdown

Thank you so much, that was helpful.

I have a question, If I want to store it on external storage, is it possible? and how can I do it? like to store it in database or server?

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

Thank you so much, that was helpful.

I have a question, If I want to store it on external storage, is it possible? and how can I do it? like to store it in database or server?

If you want to put that data in a database or on a server somewhere then you need to use fetch( ) to upload the data to a server that has scripts for handling the data. JS in the browser has a lot of security restrictions that prevent it from talking to the local file system.

Ajax (fetch) video playlist - https://www.youtube.com/watch?v=7EKebb4VUYQ&list=PLyuRouwmQCjkWu63mHksI9EA4fN-vwGs7
PHP (serverside) video playlist - https://www.youtube.com/watch?v=GBHL4QsMSfc&list=PLyuRouwmQCjlRGZETsGChIzf-M3BBqH3L
MySQL database video playlist - https://www.youtube.com/watch?v=a9W7OpS4LfI&list=PLyuRouwmQCjlXvBkTfGeDTq79r9_GoMt9
NodeJS (serverside) video playlist - https://www.youtube.com/watch?v=UMKS6su8HQc&list=PLyuRouwmQCjnr-rRrhbPrS4YQ0brDQ-14
NodeJS/Express video playlist - https://www.youtube.com/watch?v=cMbJ8hatqJ8&list=PLyuRouwmQCjne87u8XUdOM5oCl7vI2vVL

@susana141

Copy link
Copy Markdown

Thanks for sharing this, super helpful!

@vishal4735

Copy link
Copy Markdown

Line 42, is it possible , not to reset whole form but specific fields only?

I am actually trying to build multipage form, want to get JSON output.

In total there are 5 fields , only 3 changes on next page, 2 fields remains the static(or prepopulated)

Thanks

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

Yes. You don't have to reset the whole form. You can set each input's value property individually back to an empty string.

@Ehsanul-Karim-Pappu

Copy link
Copy Markdown

Thank you very much.
But if I want a JSON file, that will hold all the key-value pairs every time a user fill-up the form. And it will save the data, which can be accessed later anytime. How can I do this?

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

You need to use fetch( ) to upload the data to a server-side script that will save the data. II don't recommend saving it as a static file though. Use a database. The script will put the data into the database.

@Ehsanul-Karim-Pappu

Copy link
Copy Markdown

Thank you Sir.

@delagnese

Copy link
Copy Markdown

it doesn't work if you have multiple values to a key, does it? for example, how could I store this two values to display as json would understand? "genres": ["history", "economics"],

@praveenltmk2011

Copy link
Copy Markdown

can we store this javascript object in any exeternal file like txt file or excel.. If yes ..Please tell me how..? thanks

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

You can use fetch to upload the data to a server-side script that saves the data in a database or in a file. That is the typical use case for this.

@Darko-darko

Copy link
Copy Markdown

Hello,
I am totally beginner.
I have problem and trying find solve this a min. four days... I was learning a lot :), but...

I want to make input form with 8 boxes, and that easy... and I want to make (from them) variable...
In this tutorial finally I see how to avoid submit button... but I dont know how to create 8 variable from input text...

Thank You

@oneezy

oneezy commented Nov 10, 2020

Copy link
Copy Markdown

Excellent video! I have 2 questions...

1.) How would we NOT include key/value pair in json object if there is no value in form input?

2.) How would we create nested json object?

ghost commented Mar 20, 2021

Copy link
Copy Markdown

What is the purpose of number 2 inside pre.textContent = '\n' + JSON.stringify(movies, '\t', 2); ?
Thank you so much in advance!
I am learning a great deal from you!

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

What is the purpose of number 2 inside pre.textContent = '\n' + JSON.stringify(movies, '\t', 2); ?
Thank you so much in advance!
I am learning a great deal from you!

In this example it is the number of tab characters to place on each line.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

Excellent video! I have 2 questions...

1.) How would we NOT include key/value pair in json object if there is no value in form input?

2.) How would we create nested json object?

  1. You would have to loop through the Object and use the delete keyword to remove properties whose value was an empty string.
  2. JSON is a String. It is a string representation of whatever Object you pass to the JSON.stringify method. You don't edit the string. You change the object then stringify it.

ghost commented Mar 21, 2021

Copy link
Copy Markdown

What is the purpose of number 2 inside pre.textContent = '\n' + JSON.stringify(movies, '\t', 2); ?
Thank you so much in advance!
I am learning a great deal from you!

In this example it is the number of tab characters to place on each line.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Man,i never knew we could do something like that.Thank you so much Steve!

@PretheshP

Copy link
Copy Markdown

thank you sir

@gabelorm

Copy link
Copy Markdown

If I want to add the data to a table in a tabulated form? How can I modify this code?

@smostafad

Copy link
Copy Markdown

Screenshot (90)

Hello I have a color change and I want to download a new color I want to see if anyone can help me The color and format file is json

@ichie-Ozor

Copy link
Copy Markdown

please how do i validate if all the fields in the form is filled in before it can be submitted. thank you

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

@ichie-Ozor

ichie-Ozor commented Jan 18, 2022 via email

Copy link
Copy Markdown

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

This video - https://www.youtube.com/watch?v=gL8M9Sl5QLs is about uploading data with fetch.

I have a full playlist on how fetch / AJAX works.

It is important to note that you can't upload directly to a database. You can use fetch to send an HTTP Request that can include files or data. There needs to be a server-side script (API) that handles whatever you are sending and it will be responsible for putting things into the server-side database.

@amandakoster

Copy link
Copy Markdown

Jeez, thanks so much! I have been using React for so long I forgot how to use Vanilla! How would you access that state object elsewhere in the app? For example, 2 inputs to capture (ex.) string1 and string2, add that to a user object (done, tutorial above) and then access that object for another api call?

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

If you are talking about the movies array - in this simple example it is just a global variable.
This isn't a production ready code base though, just an illustration of some concepts for my students.
I have other videos on finite state machines, and what a reducer is - https://www.youtube.com/watch?v=TOhUqDGNFtA that help students understand the vanilla JS behind React.

@amandakoster

amandakoster commented Feb 3, 2022

Copy link
Copy Markdown

Thank you! The video reference was helpful. I like how simple and short your videos are. Very helpful!

@miriambej

Copy link
Copy Markdown

great lesson! could you please tell me how to store the form in cache API instead of localStorage? Thank you!

@prof3ssorSt3v3

Copy link
Copy Markdown
Author

Cache API stores files, not data. You would have to create a file, and write your data to that file, then save the file.

Cache API video - https://www.youtube.com/watch?v=Gu0t2EW2kfU

@PeeKay26

Copy link
Copy Markdown

Hello I'm getting the following error:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at HTMLDocument.<anonymous> (index.html:216:43) (anonymous) @ index.html:216

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment