josefarias/hotwire_combobox

Incorrect use of <label for=FORM_ELEMENT>

JoshAntBrown opened this issue · 3 comments

Most forms typically come with some sort of label, the default approach would look something like:

<%= form.label :product_id %>
<%= form.combobox :product_id, Product.all %>

However, this results in the following error being reported by the browser:

Incorrect use of <label for=FORM_ELEMENT>
The label's for attribute doesn't match any element id. This might prevent the browser from correctly autofilling the form and accessibility tools from working correctly.

To fix this issue, make sure the label's for attribute references the correct id of a form field.

The label is targeting the hidden element within the comboxbox as it is being given the generated id of the field. The label should be targeting the text input that we can interact with. Clicking the label should move our focus to the text input so we can begin typing.

Workaround
A work around for this is to modify the for attribute directly to target the id of the text input. However, this requires manual intervention from the developer.

<%= form.label :product_id, for: "formmodel_product_id-hw-combobox" %>
<%= form.combobox :product_id, Product.all %>

Possible Solution
It may be better if the id's are swapped so that the text input has the id of the field, and hidden input gets a different id. This way clicking the label and other accessibility tools will continue to work by default without intervention.

This is a great point. Thanks @JoshAntBrown! Addressed here: #20

@JoshAntBrown fixed in v0.1.31. Thanks for the report!

You'll still have to prefix the model name when using the form helper, but won't have to add the -hw-combobox suffix anymore. If I recall correctly you have to prefix the model name even when using the built-in form builder methods from Rails. Unless I'm misremembering.

Anyway, this should now behave the way other form builder methods do. Please let me know if not!

Thanks! Yeah this works great now, I was able to remove the patched for option and everything worked correctly.