Why does the check_box form helper generate two checkboxes, one hidden?

血红的双手。 提交于 2019-12-03 20:09:42

问题


this code: =form_fo :store_products do |f| = f.check_box :track_inventory

creates this html:

<input name="product_group[products_attributes][0][store_products_attributes}[1342647745501][track_inventory]" type="hidden" value="0">

<input id="product_group_products_attributes_0_store_products_attributes_1342647745501_track_inventory" name="product_group[products_attributes][0][store_products_attributes][1342647745501][track_inventory]" type="checkbox" value="1">

What is the reason for the first hidden element?


回答1:


The HTML specification says that unchecked checkboxes should not be sent by webbrowsers. This means that, if unchecked, rails receives no record of whether the checkbox on the form was unchecked. This would be important, for example, if the user was editing a record where the checkbox was previously checked and they had decided to uncheck it - rails would not know to update this attribute.

The hidden field has the same name as the checkbox, so if the checkbox is not sent, the hidden_field is sent instead (with the value of '0', meaning unchecked). This way, rails will always receive a signal as to whether the checkbox was checked or unchecked.

More information on this gotcha at APIDock



来源:https://stackoverflow.com/questions/11550941/why-does-the-check-box-form-helper-generate-two-checkboxes-one-hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!