jQuery 表单提交复选框将值设置为“on”而不是“true”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9185937/
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
form submit checkbox sets value to "on" rather than "true"
提问by Raif
Hi I have an html form which I am submitting via the click event on a button. The event fires $("#myform").submit(); the problem is that there is a checkbox on the form and in firebug under the posted params it shows "mycheckbox1 on" rather then the expected "mycheckbox1 true".
嗨,我有一个 html 表单,我通过按钮上的点击事件提交。事件触发 $("#myform").submit(); 问题是表单上有一个复选框,在发布的参数下的萤火虫中它显示“mycheckbox1 on”而不是预期的“mycheckbox1 true”。
when submitting a form via ajax I can set the data that is posted no problem but this form has a file upload which requires one of the various hacks to make it work. The one I'm using ultimately calls submit. but perhaps that is not relevant.
通过ajax提交表单时,我可以设置发布的数据没问题,但该表单有一个文件上传,需要各种技巧之一才能使其工作。我正在使用的最终调用提交。但也许这无关紧要。
In any case when the data arrives at the server, the server doesn't see the value "on" as a bool and thus ignores it.
在任何情况下,当数据到达服务器时,服务器不会将值“on”视为布尔值,因此会忽略它。
Any insight would be greatly appreciated.
任何见解将不胜感激。
回答by alex
A checked checkbox simply sends its value
attribute. An unchecked checkbox doesn't send itself in the form.
选中的复选框只是发送其value
属性。未选中的复选框不会在表单中发送自身。
Therefore, a simple test if the checkbox's name
attribute was posted can determine if it was checked or not.
因此,一个简单的测试复选框的name
属性是否被发布就可以确定它是否被选中。
回答by Meligy
Yeah, different browsers might handle checkboxes differently when the value is not set.
是的,当未设置值时,不同的浏览器可能会以不同的方式处理复选框。
You can set the value attribute of the checkbox explicitly to "true" as your server understands it when checkbox is checked and it gets sent to it. As Alex hinted in his answer, the checkbox wont be sent if it's unchecked, so, I assume the server will default to false in this case.
您可以将复选框的 value 属性显式设置为“true”,因为您的服务器在选中复选框并将其发送给它时会理解它。正如亚历克斯在他的回答中暗示的那样,如果未选中复选框,则不会发送该复选框,因此,我认为在这种情况下服务器将默认为 false。
回答by jk.
Try selecting or sending the checked
value with the form:
尝试checked
使用以下形式选择或发送值:
$("input:checked").val()