AndyM AndyM - 5 months ago 7
HTML Question

Can I Get From HTML Element to Already Existing JS Element

Background



I have a form with many text inputs (
<input type="text" />
). On pageload, I loop through the form and create a JS object variable for each one, that holds methods such as validate, and properties such as original value, current formatted value, validation requirements, etc:

field = new Field(wrapperElements[i]);


When an input has the
blur
event fired, I run validation on that field. I do this so that I can run my validation as the user is working through the form, rather than wait until the very end when the form is submitted.

I then cache the validity result in the Field object. When the user submits the form, I don't have to validate every field, I just have to check the already calculated validity, which improves speed at the end.




Problem



The user edits only one field, the cursor is still in that field, and the user hits enter. This fires the form's
submit
before firing the field's
blur
event. The form tries to submit without validating the edited field.

I know that I could just force validate all fields on
submit
, but that seems inelegant to me, and seems like wasted calculation. I just need to force validate the currently focused element, if that element is an input.




Part Solution



I've tested out
document.activeElement
, and that works. However, I can't figure out how to get the already existing JS variable that is associated with the input, from the node that
document.activeElement
returns.




Specific Question



If I have an HTML element, and I create a JS variable with it as such...

<input type="text" value="My input!" id="mainInput" />
---
var field = document.getElementById('mainInput');


... how can I get that
field
variable just from knowing returning the node again, separately, via
document.activeElement
?

Answer

One thing you can do is do the comparison of every variable with the active DOM element:

var field1 = form.children[i]
var field2 = form.children[j]
...

field1 === document.activeElement
field2 === document.activeElement

One of the statements should be true and variable inside should be reference to the active DOM element.

Comments