An HTML form is defined by the
</form> tags. Open up your code editor and make a new file called
This is an empty form, which has the
name attribute set to
<form> element. Here are some:
document.form1; // document.form-name document.forms; // 0 for 1st form, 1 for 2nd form and so on. document.forms["form1"]; // document.forms["form-name"] // there can be multiple HTML elements with the same name // hence "getElementsByName" returns an array // to get our form, we need to get the first element of the array document.getElementsByName("form1")
All of these refer to the same
<form> tag, we can add form elements like text field, checkbox, etc. A form also generally has a submit button which is used to submit the data once the user has filled the form.
Form elements are specified by using the
<input> tag. Every form element must have a
name attribute. If an element doesn’t have a
name attribute, its data is not sent. Moreover, the names must be unique. The
type attribute is used to specify the type of the input field. For example,
text means a text field,
radio is for multiple choice fields,
checkbox is for checkboxes, etc.
Let’s create a simple form.
<html> <head> <title>HTML Forms</title> </head> <body> <form name="form1"> Name: <input type="text" name="nameinput" placeholder="Enter your name.."> <br> <br> E-mail: <input type="email" name="emailinput" placeholder="Enter your email.."> <br> <br> Do you like Commonlounge? <input type="radio" name="likecommonlounge" value="Yes">Yes <input type="radio" name="likecommonlounge" value="Definitely Yes">Definitely Yes <br> <br> <input type="checkbox" name="tandc"> I accept the terms and conditions <br> <br> <input type="submit"> </form> <p id="formentries"> <!-- Ignore this paragraph for now. We'll use it soon. --> </p> </body> </html>
Note: Each input field has a unique
nameexcept for the radio type. All the options for one question have the same
Your form should look something like this:
document.form1.nameinput; document.form1.likecommonlounge; document.form1.tandc;
Tip: Again, it’s a good idea to open the console and play around with this. Because console has autocomplete, it is quite helpful in exploring what you get when you type in the above.
And we can also access the values for each form element. For example:
f.nameinput.value; // text typed by the user f.likecommonlounge.value; // "value" attribute of the selected radio button f.tandc.checked; // true if checkbox is checked, false otherwise
Now that we have a simple HTML