AutoFocus plugin

Focus on the first invalid element when submit form

Usage

You have to use this plugin with SubmitButton plugin which automatically validate the form when pressing the Submit button. The following piece of code is the starting point to use the AutoFocus plugin:
<html>
<head>
<link rel="stylesheet" href="/vendors/formvalidation/dist/css/formValidation.min.css" />
</head>
<body>
<form id="demoForm" method="POST">...</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.35.3/es6-shim.min.js"></script>
<script src="/vendors/formvalidation/dist/js/FormValidation.min.js"></script>
<script src="/vendors/formvalidation/dist/js/plugins/AutoFocus.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function(e) {
FormValidation.formValidation(
document.getElementById('demoForm'),
{
fields: {
...
},
plugins: {
autoFocus: new FormValidation.plugins.AutoFocus(),
submitButton: new FormValidation.plugins.SubmitButton(),
...
},
}
);
});
</script>
</body>
</html>
The sample code above assumes that the FormValidation files are placed inside the vendors directory. You might need to change the path depending on where you place them on the server.

Options

OptionTypeDescription
onPrefocusFunctionInvoked before the first invalid element get focused
The onPrefocus function accepts one parameter:
onPrefocus: function(e) {
// e.field: The field element name
// e.firstElement: The first invalid element
}

Basic example

Try to press the Add product button to see the first invalid field will be focused. Then fill in the Product name, press the Add product button again. The plugin will bring focus to the Description field which now becomes the first invalid field.
AutoFocus plugin

Changelog

v1.6.0
  • The onPrefocus option allows to access the file name via the field property
v1.5.0
  • Fixed an issue that the AutoFocus plugin doesn't work. From v1.5.0, it becomes an external plugin
v1.3.0
  • Added onPrefocus option that is useful when you want to activate the tab containing the first invalid field
v1.0.0
  • First release