jQuery序列化不注册复选框 [英] jQuery serialize does not register checkboxes

查看:83
本文介绍了jQuery序列化不注册复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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序列化表格数据的方式与浏览器的方式不同,那么您就消除了表格降级的任何可能性.如果您仍然绝对需要这样做,只需使用<select>框,并选择是/否".至少到那时,禁用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>

我以前在某些网站上看到过这种用法,并且总是对自己说,为什么他们不只是使用复选框" <​​/em>?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆