I need assistance with a form that has 4 fields. I would like the first field to have the autofocus
so it is the first one the user fills out. However, when the user navigates to the second field, whether by tab or mouse, I want the cursor to automatically move to the end of the string in that field. The field contains a pre-filled string.
I am using Django and have a form widget controlling the attributes. I've been able to display the string and move the cursor to the end, but this also triggers the autofocus
on the second field. I haven't been able to achieve both functionalities simultaneously.
Here is the code I have implemented:
Django
field = forms.URLField(
widget = forms.URLInput(
attrs = {
'placeholder': 'enter field',
# call to javascript function - this works
'onfocus': 'add_string("field_id", "string")',
}
)
)
JavaScript:
// add string to element
function add_string(id, string) {
var input = document.getElementById(id);
input.value = string;
}
I have experimented with various JavaScript scripts without success. Then, I discovered setSelectionRange
and tried incorporating it like this:
input.setSelectionRange(7, 7)
Where 7 represents the end of the specific "string" in the onfocus
JavaScript function call, but unfortunately, I couldn't get it to work...
Lastly, I tried utilizing some jQuery code like this:
// focus after string, no highlight
$(document).ready(function() {
var $field = $("#field_id");
var old_val = $field.val();
$field.focus().val('').val(old_val);
});
However, this resulted in the same outcome: initial focus on the second field and the cursor moving to the end.
Do you have any suggestions on how I can achieve both autofocus
on the first field and have the cursor jump to the end of the pre-filled string in the second field upon its focus? It would be a neat trick if I could figure out how to accomplish this.