Vuelva a establecer el foco después de enviar el formulario (javascript)

I have some input fields on my form that require submit on change. When they are submitted I lose the focus. I want to have my focus back on my input. I wanted to use that:

Event.observe(document, 'dom:loaded', $('" + focusedFieldId + "').focus());

where focusedFieldId is id of changed element. Sometimes it works fine but sometimes I got null value in my input. When I change focusedFieldId to some other field id it works fine (it sets the value and then focus on field). The problem is only when I try set focus back on the same input. One important issue: after value change some javascript is fired ( After this javascript form is submitted and then I want to set focus back. I thought that when dom is loaded it means that submit is over, page is reloaded and I'm ready to set focus back. Where do I make mistake?

preguntado el 31 de julio de 12 a las 14:07

I'd test to make sure '" + focusedFieldId + "').focus() exists in the DOM at the time this code is executed. Check to see if there element is there first. -

$('" + focusedFieldId + "') exists while executing action -

1 Respuestas

I believe you're falling in some sort of race condition here. There are two main, different "onLoad" events you can observe with prototype.js

One of them is what you just used here:

document.observe("dom:loaded", function() { ... });

otro seria

Event.observe(window, "load", function() { ... });

Las en el primer one will be executed as soon as the DOM (read: HTML) is loaded by the browser and the segundo cuando everything is loaded.

If you are setting your focusedFieldId in some script above that, I would strongly suggest going for the 2nd event observer; even though it's slower, it will make sure your previous scripts are parsed.

This still is a design flaw though. I would strongly suggest you putting todos of the screen controller logic (including the variable asignment) within the first onLoad event for much faster execution and avoid potential race conditions like this one.

contestado el 03 de mayo de 13 a las 22:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.