@@ -234,6 +234,9 @@ function preventUnload(event) {
234234
235235 // Only display errors if this is the form that was submitted
236236 if (submittedFormId && submittedFormId === currentFormId) {
237+ var firstErrorField = null ;
238+ var firstErrorTab = null ;
239+
237240 $ .each (errors, function (bag , errorMessages ){
238241 $ .each (errorMessages, function (inputName , messages ) {
239242 var normalizedProperty = inputName .split (' .' ).map (function (item , index ){
@@ -246,6 +249,17 @@ function preventUnload(event) {
246249 $ (' #' + currentFormId + ' [name="' + normalizedProperty + ' "]' ),
247250 container = field .closest (' .form-group' );
248251
252+ // Store the first error field for focusing
253+ if (firstErrorField === null && field .length > 0 ) {
254+ firstErrorField = field .first ();
255+ @if ($crud -> tabsEnabled () )
256+ var tab_container = $ (container).closest (' [role="tabpanel"]' );
257+ if (tab_container .length ) {
258+ firstErrorTab = tab_container .attr (' id' );
259+ }
260+ @endif
261+ }
262+
249263 // iterate the inputs to add invalid classes to fields and red text to the field container.
250264 container .find (' input, textarea, select' ).each (function () {
251265 let containerField = $ (this );
@@ -278,6 +292,28 @@ function preventUnload(event) {
278292 });
279293 });
280294 });
295+
296+ // Focus on the first error field
297+ if (firstErrorField !== null ) {
298+ @if ($crud -> tabsEnabled () )
299+ // Switch to the tab containing the first error if needed
300+ if (firstErrorTab) {
301+ $ (' .nav a[href="#' + firstErrorTab + ' "]' ).tab (' show' );
302+ }
303+ @endif
304+
305+ // Focus on the first error field
306+ setTimeout (function () {
307+ const fieldOffset = firstErrorField .offset ().top ;
308+ const scrollTolerance = $ (window ).height () / 2 ;
309+
310+ triggerFocusOnFirstInputField (firstErrorField);
311+
312+ if (fieldOffset > scrollTolerance) {
313+ $ (' html, body' ).animate ({scrollTop: (fieldOffset - 30 )});
314+ }
315+ }, 100 );
316+ }
281317 }
282318 @endif
283319
0 commit comments