If you have a reference to any field in the form or an event then you don't need to explicitly look up the form since every form field has a form
attribute that points to its parent form (if there is one, of course). That means that once you have a field reference to a DOM element userName
then userName.form
will be the form. If $userName
is a jQuery object, then $userName.get(0).form
will give you the form.
If you have an event then it will contain a target
attribute which will point to the form field that triggered the event, which means you can access the form via myEvent.target.form
.
Here is an example without any form lookup code.
function doLogin(e) {
e = e || window.event;
e.preventDefault();
// e.target is the submit button
var form = e.target.form;
if (form.login.value && form.password.value) {
alert("Submitting form — user:" + form.login.value + " password:" + form.password.value);
form.submit();
} else {
alert('Please fill in the form!');
}
}
<html>
<body>
<form name="frm">
<input type="text" name="login"><br />
<input type="password" name="password"><br />
<button type="submit" onclick="doLogin()">Login</button>
</form>
</body>
</html>
If you have multiple forms on the page you still don't need to label them by name or id, because you'll always get the correct form instance via the event or via a reference to a field.