You are given the following form and asked to complete a simple task to gather data from the form fields
index.html
<div class="container">
<div class="header"> <h4> Register </h4>
</div>
<form class="myForm">
<div class="message">
<label for="msg">Message</label>
<textarea id="msg"></textarea>
</div>
<div class="contact">
<label for="name">Name</label>
<input type="text" id="name">
<label for="favSong">Your favourite song</label>
<input type="text" id="favSong">
<label for="email">Email Address</label>
<input type="email" id="email">
<label>Choose Image for your profile</label>
<input type="file" name="profile-image" id="form-profile-image" accept="image/*">
<button onclick="submitProfile()" >Submit</button>
</div>
</form>
</div>
<script src="src/index.js"></script>
Task
Using the FormData web API complete the submitProfile() function which will let us send post data of the field values to API URL given below
//index.js
const API_URL = "http://localhost:3000/api/user";
const submitProfile = ()=>{
//complete the code
}
The example post object should look like this
{
name:"",
msg:"",
email:"",
imageFile:"",
favSong:""
}
Steps to solving this
Assign a variable to the value of the field using getElementByID, for example for name we can something like
const name=document.getElementById('name')
Initialize formData() and assign it to a variable 'data'
Append all the values to
data
variable using .append()Then use fetch() to post the data object to the API url given.
These steps can be implemented as follows
Complete code for this can be found here https://codesandbox.io/s/shy-moon-n0jdtx?file=/index.js
Top comments (4)
The code you wrote, can be refactored and improved, so here are some tips:
<button type="submit">
, clicking it will submit the form. It's better to watch for form submitting event than the button click.new FormData
, you can pass the form object itself. So your entiresubmitProfile
function can become so much shorter, something like:formProps
will be an object, having your form data. Also, this way you won't have to specify and find each form input field.Even cleaner would be to use the
onsubmit
property of the HTML form:As long as a button is inside form tag it will submit by default so no need for the type unless you want to be explicit
Thanks!!