serializeJSON 对checkbox
时间: 2023-07-29 19:10:39 浏览: 44
如果要使用 jQuery 的 serializeJSON 方法将表单中的 checkbox 值序列化为 JSON 字符串,需要注意以下几点:
1. 在 HTML 中,每个 checkbox 都应该有一个唯一的 name 属性。
2. checkbox 的值应该设置为一个字符串,如 `value="true"` 或 `value="false"`。
3. 如果 checkbox 被选中,则它的值会被序列化为 JSON 字符串中的 true 或 false。
以下是一个示例 HTML 表单:
```html
<form id="my-form">
<input type="text" name="name" value="John" />
<input type="checkbox" name="isMarried" value="true" checked="checked" />
<input type="checkbox" name="hasChildren" value="true" />
<button type="submit">Submit</button>
</form>
```
以下是使用 serializeJSON 方法将表单序列化为 JSON 字符串的示例代码:
```javascript
$('#my-form').submit(function(event) {
event.preventDefault();
var formData = $(this).serializeJSON();
console.log(formData);
});
```
输出结果:
```json
{
"name": "John",
"isMarried": true,
"hasChildren": false
}
```
在上述示例中,`isMarried` checkbox 被选中,其值被序列化为 true;而`hasChildren` checkbox 未被选中,其值被序列化为 false。注意,如果 checkbox 没有被选中,则在序列化的 JSON 字符串中不会包含该属性。