How to Create a Simple Form Using HTML and JavaScript?

Estimated read time 2 min read

To create a simple form using HTML and JavaScript, follow these steps:

  1. Create the HTML structure: Use the <form> element to define the form and its contents. Inside the form, use form elements such as <input>, <textarea>, and <select> to capture user input.
  2. Add form labels: Use the <label> element to provide descriptive labels for each form element. This helps the user understand what information they need to enter.
  3. Style the form: You can use CSS to style the form and its elements. You can control the layout, colors, font sizes, and other design aspects.
  4. Add form validation: You can use JavaScript to validate the form data before submitting it. You can check if required fields are filled, if the input data is in the correct format, or if the values are within a specific range.
  5. Submit the form data: Use JavaScript to submit the form data to a server-side script or a database. You can use the submit event and the FormData object to get the form data.

Here is an example of a simple HTML form with JavaScript validation:

HTML:

<form>
  <label for="name">Name:</label>
  <input type="text" id="name" required><br><br>
  <label for="email">Email:</label>
  <input type="email" id="email" required><br><br>
  <input type="submit" value="Submit">
</form>

JavaScript:

const form = document.querySelector("form");
form.addEventListener("submit", function(event) {
  event.preventDefault();
  const name = document.getElementById("name").value;
  const email = document.getElementById("email").value;
  if (!name || !email) {
    alert("Please fill out the form");
  } else {
    alert(`Name: ${name} Email: ${email}`);
  }
});

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply