用 true 或 false 将复选框值存储在 JSON 中

Store checkbox values in JSON with true or false

我在用户提交表单时获取复选框的值并将其值存储为数组,因此表单如下所示:

<!-- gym_create.html - I have removed the other inputs in the form for brevity -->

<form class="create-gym" role="form">
  <input type="checkbox" name="gymTags" value="Bodybuilding" id="tagBodybuilding" class="tag-checkbox"/>
  <input type="checkbox" name="gymTags" value="Powerlifting" id="tagPowerlifting" class="tag-checkbox"/>
  <button type="submit" class="btn create-form-submit">Save gym</button>
</form>

然后我在与表单关联的 JS 文件中收集该信息:

// gym_create.js - I have removed the other values I collect apart from the gymName value for brevity

Template.gymCreate.events({
  "submit .create-gym": function (e) {

    e.preventDefault();

    var tagOutput = JSON.stringify({
    tagOutput: $(':checkbox[name=gymTags]:checked').map(function() {
        return $(this).val();
      }).get()
    });

    // Collect values from form when submitted
    var gymDetails = {
      gymName: $(e.target).find('[name=gymName]').val(),
      gymTags: tagOutput,
    }

    // Call method here
  }
});

然后我可以使用 {{gymDetails.gymTags}} 在我的模板中输出这些,但这会在浏览器中产生以下内容:

"{"TAGOUTPUT":["BODYBUILDING","POWERLIFTING"]}"

我想要的是一种将值存储为 JSON 的方法,所以它们就像这样:

{"gymTags": {
  "bodybuilding": "true",
  "powerlifting": "false"
}}

这样我就可以单独输出每个标签,也可以只访问 'true'(已检查)的标签。

有人知道我是怎么做到的吗?我昨天一直在争论,我能想到的最好的是 =JSON.stringify

我不想将整个表单传递给 JSON,只是复选框是 JSON.stringify 我想做的,或者我找错了树。

我认为应该这样做。您只是 return 计算了输入的值。您想要 return 一个 json 对象,其中 value 是 "index" 而 checked 属性 是 "value"对象。

var tagOutput = JSON.stringify({
    tagOutput: $(':checkbox[name=gymTags]').map(function() {
        var op = {};
        op[this.value] = this.checked;
        return op;
    }).get()
});

编辑:如 Da Rod 所述,要同时使用已选中和未选中的复选框,您必须删除“:checked”选择器。

由于您的选择器只抓取选中的项目,因此它们都是 "true"。既然如此,您需要更改使用 "map" 的方式来向 tagOutput 添加属性。

var tagOutput = {}
$(':checkbox[name=gymTags]').map(function() {
        tagOutput[this.value] = this.checked;
    })
});