Skip to content

Commit

Permalink
Issue backdrop#3166: Retain field focus after autosubmit replaces a f…
Browse files Browse the repository at this point in the history
  • Loading branch information
argiepiano committed Mar 8, 2024
1 parent 414ca7c commit 9490ad3
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions core/misc/autosubmit.js
Expand Up @@ -37,12 +37,37 @@
Backdrop.behaviors.autosubmit = {
attach: function(context) {
// 'this' references the form element
function triggerSubmit (e) {
function triggerSubmit (element) {
var $this = $(this);

// Variable "element" will have a value only when text fields trigger
// this. If element is undefined, then remove the data to prevent
// potential focus on a previously processed element.
if (element === undefined) {
$('body').removeData('autosubmit-last-focus-id');
}
else {
$('body').data('autosubmit-last-focus-id', $(element).attr('id'));
}

// Submit the form.
$this.find('.autosubmit-click').trigger('click');
}

// the change event bubbles so we only need to bind it to the outer form
// Listener to ajaxStop will re-focus on the text field as needed.
$(document).off('ajaxStop.autosubmit').on('ajaxStop.autosubmit', function () {
let id = $('body').data('autosubmit-last-focus-id');
if (id === undefined) {
return;
}
let $textInput = $('#' + id);
let pos = $textInput.val().length;
$textInput.focus();
$textInput[0].setSelectionRange(pos, pos);
$('body').removeData('autosubmit-last-focus-id');
});

// The change event bubbles so we only need to bind it to the outer form.
$('form.autosubmit-full-form', context)
.add('.autosubmit', context)
.filter('form, select, input:not(:text, :submit)')
Expand Down Expand Up @@ -86,12 +111,14 @@ Backdrop.behaviors.autosubmit = {
})
.on('keyup', function(e) {
if ($.inArray(e.keyCode, discardKeyCode) === -1) {
timeoutID = setTimeout($.proxy(triggerSubmit, this.form), 500);
// Provide the target element to triggerSubmit.
timeoutID = setTimeout($.proxy(triggerSubmit, this.form, e.target), 500);
}
})
.on('change', function (e) {
if ($.inArray(e.keyCode, discardKeyCode) === -1) {
timeoutID = setTimeout($.proxy(triggerSubmit, this.form), 500);
// Provide the target element to triggerSubmit.
timeoutID = setTimeout($.proxy(triggerSubmit, this.form, e.target), 500);
}
});
});
Expand Down

0 comments on commit 9490ad3

Please sign in to comment.