Save Username to Local Storage
We want the username that is put into the first idea submit into local storage and then pre-fill the username field with that value.
Go into components/ideaForm.js and add the following code:
async handleSubmit(e) {
e.preventDefault();
if (
!this._form.elements.text.value ||
!this._form.elements.tag.value ||
!this._form.elements.username.value
) {
alert('Please enter all fields');
return;
}
// Save user to local storage
localStorage.setItem('username', this._form.elements.username.value); // <--- Add this line
// ...
// Render the form again
this.render();
document.dispatchEvent(new Event('closemodal'));
}
Pre-fill The Username Field
In the render method, add the following code:
render() {
this._formModal.innerHTML = `
<form id="idea-form">
<div class="form-control">
<label for="idea-text">Enter a Username</label>
<input type="text" name="username" id="username" value="${
localStorage.getItem('username') ? localStorage.getItem('username') : ''
}" />
</div>
<div class="form-control">
<label for="idea-text">What's Your Idea?</label>
<textarea name="text" id="idea-text"></textarea>
</div>
<div class="form-control">
<label for="tag">Tag</label>
<input type="text" name="tag" id="tag" />
</div>
<button class="btn" type="submit" id="submit">Submit</button>
</form>
`;
this._form = document.querySelector('#idea-form');
this.addEventListeners();
}
Now, it will fetch the username from local storage and pre-fill the username field.