This is the 9th day of my participation in Gwen Challenge
In modern front-end development, with the help of THE MVVM framework and XHR, we can be very flexible to submit data to the server, so the use of forms is less and less, but in terms of semantics and old project maintenance, forms still play an important role, so we still need to learn the features of forms.
First, basic knowledge
The form is represented by the
- Name: indicates the form name
- Elements: A collection of all controls in a form (HTMLCollection)
- Action: URL to accept the request
- Method: indicates the request type, such as GET and POST
- Reset: Resets the form field to the default value
- Submit: Submit the form
Use Document. forms to get all the forms on a page.
Commit and reset
and
const form = document.getElementById('myForm')
form.addEventListener('submit'.function(event){
// Check parameters
//
// Cancel the submission
e.preventDefault(event);
})
Copy the code
Instead of using input and button, you can call the submit method directly:
const form = document.getElementById('myForm')
/ / submit
form.submit()
Copy the code
To reset the form, simply change the type of the input or button to ‘reset’, similar to submit.
Form fields
Form elements can be accessed using the same old DOM methods as any other element on the page. In addition, each form has a elements attribute that represents a collection of elements, such as:
<form id="form1">
<input name="textbox1" value="xxx">
</form>
Copy the code
const form = document.getElementById('form1')
// subscript fetch
const field1 = form.elements[0];
/ / the name
field2 = form.elements['textbox1']
Copy the code
When multiple form controls use the same name, a NodeList is returned:
<form method="post" id="myForm">
<ul>
<li><input type="radio" name="color" value="red">Red</li>
<li><input type="radio" name="color" value="green">Green</li>
<li><input type="radio" name="color" value="blue">Blue</li>
</ul>
</form>
Copy the code
const form = document.getElementById("myForm");
const colorFields = form.elements["color"];
alert(colorFields.length); / / 3
const firstColorField = colorFields[0];
const firstFormField = form.elements[0];
alert(firstColorField === firstFormField); //true
Copy the code
Four, feeling
In the early days, form was an important way for the front-end to submit data to the server, but it caused page refresh, inflexible use and other problems. In modern front-end development, it is rarely used to submit data. However, we can still use the form’s built-in Submit and reset mechanisms to simplify form validation and reset, and use them to improve code semantics, so it’s important to know the basics of forms.