Get forms and controls
Document methods/properties | illustrate |
getElement... or querySelect... method | |
forms | collection object (all forms) |
Form object.elements returns a collection object composed of all controls
example:
<form name="login">
<input name="user"></form>
let loginForm=document.forms[0];//["login"]
let form=document.elements;//所有控件
let username=elements.user;//input所有控件
A concise way to get forms and controls
Get the form: document.form name attribute value
Get control: form object. Control name or id attribute value
<form name="login">
<input type="text" name="user" id="user1">
<input type="tel" name="tel" id="tel">
</form>
let loginForm=document.login;
let user=loginForm.user;
let tel=loginForm.tel;
Control properties, methods, events
Common properties and methods of controls
Works with most controls
properties/methods | illustrate |
type | The type of control used for input elements |
value | the value of the control |
readonly | If the value is true, the control is read-only and can get focus but cannot be edited |
disabled | If the value is true, the control is disabled and cannot get focus and edit |
select() | Select all content in type=text or textarea elements |
focus() | Make the control get the focus and trigger the focus event |
Form control common events
event | trigger |
input | 当input,select |
change | When the value of the element is changed and submitted, it is used when the value of the select, radio, and checkbox controls change |
Radio and checkbox attributes
checked attribute: Determine whether the radio or check box is selected. Read/write, true is selected, false is vice versa
<form name="login">
<input type="checkbox" name="hobby">
</form>
document.login.hobby.onchange=function(e){
if(e.target.checked){}
}
select control properties
Attributes | method |
value | Get the option value of the select control |
options | A collection of all option elements |
SelectedIndex | The index number of the currently selected option |
Selected | Determine whether the option in the list box is selected |
<select name="my"><option></option></select>
my.value;
my.options[my.selectedIndex].value;
my.options[my.selectedIndex].text;
Form front-end validation
Verify event
Events for verification
event | illustrate |
blur | Validate when the control loses focus |
change | Validate when the value of the control changes |
input | When the textbox or textarea value changes |
keyup | Validate text boxes, input of keys in text fields |
submit | When the form is submitted to the server |
Validate the form when the form is submitted
form.addEventListener('submit',e=>{
if(form.username.value.length<8){
tipMessage.textContet='长度错误';
e.preventDefault();
return false;}
});