Javascript jQuery 表单帖子将布尔复选框转换为“开”和“关”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5317664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:37:57  来源:igfitidea点击:

jQuery form post converts boolean checkboxes to "on" and "off"?

javascriptjquery

提问by chum of chance

I have a fairly simple form with a checkbox, and I noticed that my checkbox values weren't being picked up on my server side app:

我有一个相当简单的带有复选框的表单,我注意到我的复选框值没有在我的服务器端应用程序中被选中:

$.post('CreateForm', $('#new-form').serialize(), ...

Everything else posts correctly, but I'm seeing in Firebug that it'll serialize the checkbox value as "on" or "off" instead of "true" and "false" that I get with a normal <form method="post" action="formpage">... what's going on here, is this expected behavior? My server side model binder doesn't equate "on" with "true" and thus drops the value. Obviously I could change the model binder, but wanted to make sure I wasn't doing it wrong.

其他所有内容都正确发布,但我在 Firebug 中看到它会将复选框值序列化为“on”或“off”而不是“true”和“false”,这是我在正常情况下得到的<form method="post" action="formpage">......这里发生了什么,这是预期的行为吗?我的服务器端模型绑定器不等于“on”与“true”,因此降低了该值。显然我可以更改模型活页夹,但想确保我没有做错。

Edit:

编辑:

Here's my markup:

这是我的标记:

<input type="checkbox" name="CheckboxValue" >

jQuery version 1.4.4

jQuery 版本 1.4.4

In Firebug here's the resulting post:

在 Firebug 中,结果是这样的:

... other variables &CheckboxValue=on

回答by Rocket Hazmat

The problem is that your checkboxes do not have valueattributes. When jQuery serializes the form, it uses 'on' as the default value.

问题是您的复选框没有value属性。当 jQuery 序列化表单时,它使用 'on' 作为默认值。

You should give your checkbox a value:

你应该给你的复选框一个值:

<input type="checkbox" name="CheckboxValue" value="true" />

See example here: http://jsfiddle.net/U6Sbw/1/

请参阅此处的示例:http: //jsfiddle.net/U6Sbw/1/

回答by Tao

A little late, but just in case someone stumbles across this: if you also want falsevalues to be output, this jQuery plugin provides the option to always ignore the checkbox's "value" and instead serialize it as "true" or "false":

有点晚了,但以防万一有人偶然发现:如果您还希望输出值,则此 jQuery 插件提供了始终忽略复选框的“值”并将其序列化为“真”或“假”的选项:

http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/

http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/

回答by Ryan Reynolds

Here is what i did which seems to work great. Am using js2form to marshall to sping mvc/Hymanson controller.

这是我所做的,似乎效果很好。我正在使用 js2form 来编组到 sping mvc/Hymanson 控制器。

Have a function I run with the following:

有一个我运行的功能如下:

$('input[type=checkbox]').unbind('click.checks').bind('click.checks', function(e){
    $(this).val($(this).is(':checked'));
});