randomIdeas/components/IdeaForm.js

57 lines
1.9 KiB
JavaScript

class IdeaForm {
constructor() {
this._formModal = document.querySelector('#form-modal');
}
//add all event listeners in a function
addEventListeners() {
this._form.addEventListener('submit', this.handleSubmit.bind(this));
}
handleSubmit(e) {
e.preventDefault(); //stops the submit and allows us to determine when it should run
//grabs values from the form
const idea = {
text: this._form.elements.text.value,
tag: this._form.elements.tag.value,
username: this._form.elements.username.value,
};
//clear form fields after submit
this._form.elements.text.value = '';
this._form.elements.tag.value = '';
this._form.elements.username.value = '';
//using the dispatch event method of the document object to dispatch a custom event
//to the Modal from the IdeaForm, telling the Modal to close the form on submit
document.dispatchEvent(new Event('closemodal'));
}
//create a render function like react that will output the HTML
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" />
</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(); //added within the render function because the HTML above is only available
//in the DOM after the render function is called.
}
}
export default IdeaForm;