Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kevin Dunn
6,623 PointsHow to reset a contact form with Javascript?
I have a contact form on my website and I want the contact form input fields to be cleared after the user clicks the Send Email button. I keep getting this error message "Uncaught TypeError: Cannot read property 'reset' of null at HTMLInputElement.<anonymous>". I am using Javascript and PHP.
Here are my codes:
const sendEmail = document.getElementById('sendEmail');
const contactMeForm = document.getElementById('contact-me-form');
//Remove text after sending email
sendEmail.addEventListener('click', function(){
document.getElementById("contactMeForm").reset();
});
<?php
$userName = $_POST['userName'];
$userEmail = $_POST['userEmail'];
$userMessage = $_POST['userMessage'];
$to = "test@textemail.com";
$subject = "New Message";
mail ($to, $subject, $userMessage, "From: " . $userName);
?>
<form id="contact-me-form" action="form_process.php" method="post">
<input type="text" name="userName" placeholder="Your Name">
<input type="email" name="userEmail" placeholder="Email Address">
<textarea name="userMessage" placeholder="Type Your Message Here"></textarea>
<input id="sendEmail" type="submit" name="userSubmit" value="Send">
</form>
Thanks!
2 Answers
Alexander Acker
18,123 PointsYou've created a constant on the input element called 'contactMeForm' thus no need to include the document object. Should be able to just utilize contactMeForm.reset() to get this to work.
Joseph Frazer
5,404 PointsTry setting the input value to an empty string.
Kevin Dunn
6,623 PointsKevin Dunn
6,623 PointsThanks a lot! That worked.