jQuery 序列化不注册复选框 [英] jQuery serialize does not register checkboxes
问题描述
我正在使用 jQuery.serialize 来检索表单中的所有数据字段.
I'm using jQuery.serialize to retrieve all data fields in a form.
我的问题是它不会检索未选中的复选框.
My problem is that it does not retriev checkboxes that is not checked.
它包括:
<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />
但不是这个
<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />
如何获取未选中复选框的值"?
How can I get "values" of checkboxes that is not checked?
推荐答案
jQuery serialize
密切模仿标准表单在附加到查询字符串或 POST 正文之前如何被浏览器序列化要求.浏览器不包含未选中的复选框,这确实有意义,因为它们具有布尔状态——它们要么被用户选中(包含),要么未被用户选中(不包含).
jQuery serialize
closely mimics how a standard form would be serialized by the browser before being appended to the query string or POST body in the request. Unchecked checkboxes aren't included by the browser, which makes sense really because they have a boolean state -- they're either selected by the user (included) or not selected by the user (not included).
如果你需要它在序列化中,你应该问自己为什么?为什么不检查它在数据中的存在?".
If you need it to be in the serialized, you should ask yourself "why? why not just check for its existence in the data?".
请记住,如果 JavaScript 序列化表单数据的方式与浏览器的行为方式不同,那么您就消除了表单优雅降级的任何机会.如果您仍然绝对需要这样做,只需使用带有 Yes/No 选项的 框即可.至少,禁用 JS 的用户不会与您的网站疏远,您也不会违反 HTML 规范中定义的行为.
Bear in mind that if the way JavaScript serializes form data behaves differently to the way the browser does it then you're eliminating any chance of graceful degradation for your form. If you still absolutely need to do it, just use a <select>
box with Yes/No as options. At least then, users with JS disabled aren't alienated from your site and you're not going against the defined behaviour in the HTML specification.
<select id="event_allDay" name="event_allDay">
<option value="0" selected>No</option>
<option value="1">Yes</option>
</select>
我过去曾在某些网站上看到过这种做法,并且一直在想,他们为什么不使用复选框"?
I've seen this employed on some sites in the past and always thought to myself, "why don't they just use a checkbox"?
这篇关于jQuery 序列化不注册复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!