Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gravity Wiz // Gravity Forms // Give First Validation Error Focus
<?php
/**
* Gravity Wiz // Gravity Forms // Give First Validation Error Focus
* http://gravitywiz.com/
*
* Plugin Name: Gravity Forms First Error Focus
* Plugin URI: https://gravitywiz.com/make-gravity-forms-validation-errors-mobile-friendlyer/
* Description: Automatically focus (and scroll) to the first field with a validation error.
* Author: Gravity Wiz
* Version: 1.1
* Author URI: http://gravitywiz.com/
*/
add_filter( 'gform_pre_render', 'gw_first_error_focus' );
function gw_first_error_focus( $form ) {
add_filter( 'gform_confirmation_anchor_' . $form['id'], '__return_false' );
?>
<script type="text/javascript">
if( window['jQuery'] ) {
( function( $ ) {
$( document ).bind( 'gform_post_render', function() {
// AJAX-enabled forms will call gform_post_render again when rendering new pages or validation errors.
// We need to reset our flag so that we can still do our focus action when the form conditional logic
// has been re-evaluated.
window['gwfef'] = false;
gwFirstErrorFocus();
} );
$( document ).bind( 'gform_post_conditional_logic', function( event, formId, fields, isInit ) {
if( ! window['gwfef'] && fields === null && isInit === true ) {
gwFirstErrorFocus();
window['gwfef'] = true;
}
} );
function gwFirstErrorFocus() {
var $firstError = $( 'li.gfield.gfield_error:first' );
if( $firstError.length > 0 ) {
$firstError.find( 'input, select, textarea' ).eq( 0 ).focus();
$firstError[0].scrollIntoView();
}
}
} )( jQuery );
}
</script>
<?php
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.