Today you'll learn how to let users "talk" to your website. We'll build an HTML form to collect information and use JavaScript to process it, a key skill for creating interactive applications like login pages, search bars, or contact forms.
Forms are the main way websites get information from users. Without them, you couldn't log in, post a comment, buy a product, or even search for a video. Learning to handle forms is a giant leap towards building real, useful web applications.
onsubmit event in
JavaScript.
Let's look at the key HTML tags and JavaScript ideas for making forms work.
onsubmit attribute to tell it
which JavaScript function to run when the user hits the submit button.
getElementById(), you can use the
.value property to get the text or data that the user has entered into it.
<input> tag. It tells the
browser not to let the user submit the form if that field is empty. It's a simple and
easy way to make sure you get the data you need!
In the editor, you'll find an empty `handleDemoSubmit()` function with step-by-step hints. Your job is to fill in the missing code to make the form collect and display user input when submitted!
Always start form functions with event.preventDefault() to stop the page from reloading. Then get input values with element.value!
event.preventDefault();const name = document.getElementById('nameInput').value;const color = document.getElementById('colorInput').value;if (name.trim() === '') { alert('Please enter your name!'); return; }document.getElementById('formResult').innerHTML = '<div class="alert alert-success">Name: ' + name + ', Color: ' + color + '</div>';required to the name input: <input type="text" id="nameInput" class="form-control" required>Try adding a new field to your form. How about a <textarea> for comments, or a
set of radio buttons for a multiple-choice question? See if you can get the data from your new
inputs and display it on submission.