Form in HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" name="hello" id="login"> <input type="text" placeholder="demo@email.com" <button>提交</button> </form> </body> </html>
Utilizedocument.forms
Get all forms of the current page
##document.forms[0]Get the first form of the current page A form
document.forms['hello']Get the form through the name attribute of the form
document.forms['login']Get the form through the id attribute of the form
<script> //form console.log(document.forms); // <form action="" name="hello" id="login"> console.log(document.forms[0]); console.log(document.forms['hello']); console.log(document.forms['login']); console.log(document.forms.item(0)); console.log(document.forms.item("hello")); console.log(document.forms.item("login")); //推荐 id console.log(document.forms.namedItem("login")); console.log(document.forms.hello); console.log(document.forms.login); </script>
The above is the detailed content of How to get form elements in JavaScript. For more information, please follow other related articles on the PHP Chinese website!