Pregunta

I have a form with 4 fields. I want the first of the four to have the autofocus and be the first the user fills out. But then, either by tab or mouse or whatever, when the user gets to second field, I want the cursor to end up at the end of the string to start. There is a pre-filled string in that field.

I'm using Django so I have a form widget controlling the attributes. I can get the string to show up and even get the cursor to the end, but this always causes autofocus as well on that second field. I haven't managed to get both.

Here is code I'm using so far:

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've played around with various JS scripts but to no avail. I then found setSelectionRange and played around with this like so:

input.setSelectionRange(7, 7)

Where 7 would be end of the particular "string" in the onfocus JavaScript function call, but I could't get this to work...

Finally, I played around with some jQuery that looked 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);
});

But this did the same thing: brought initial focus to second field and brought cursor to the end.

Any idea how I can do this, get both autofocus on field one but get cursor to jump to end of pre-filled string of field two on it's focus? Might be a nice trick if I knew how to do it.

¿Fue útil?

Solución

You're almost there, you just need to fire your code when your form field is focused, instead of on document ready. In my tests it was necessary to add a zero timeout, because otherwise the field value remains selected:

$(document).ready(function() {
    var $field = $("#field_id");
    $field.on('focus', function() {
        setTimeout(function() {
            var old_val = $field.val();
            $field.val('').val(old_val);
        }, 0);
    });
});

JSFiddle demo

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top