【问题标题】:Get each checked checkbox value获取每个选中的复选框值
【发布时间】:2017-01-05 01:06:11
【问题描述】:

我正在尝试获取已选为 true 的每个复选框的值。每次我选择一个复选框时,它都会获取该复选框的值,而不是所有选定的复选框。

路径:talentList.html

<fieldset>        
  <div class="checkbox">
    <label>
      <input name="specialisation" type="checkbox" value="Accounting Firm"> Accounting Firm
    </label>
  </div>

  <div class="checkbox">
    <label>
      <input name="specialisation" type="checkbox" value="Accounting in Industry"> Accounting in Industry
    </label>
  </div>
</fieldset>

路径:talentList.js

Template.talentList.events({
    'change [name="specialisation"]': function ( event, template ) {
        let specialisation = event.target.value;
        template.candidateListFilter.set( specialisation );
    }
});

【问题讨论】:

  • 我不清楚你的问题是什么。每当您选择一个复选框时,您是否试图获取所有选定的复选框值?
  • 是的,没错

标签: meteor meteor-blaze


【解决方案1】:

在事件处理程序中只设置了一个目标,因此event.target.value 将是一个标量而不是一个数组。您需要遍历复选框数组。

Template.talentList.events({
  'change [name="specialisation"]': function ( event, template ) {
    $.each($('[name="specialisation"]'),function(i,cb){
      let specialisation = cb.value;
      template.candidateListFilter.set( specialisation );
    });
  }
});

老实说,这似乎是一种奇怪的模式。如果您想在选中/取消选中复选框时更新文档,则不必同时设置所有其他复选框的状态,您应该可以只戳您想要的。

【讨论】:

  • 添加 "[name='specialisation']:checked" 所以它只抓取选中的复选框。
【解决方案2】:

不确定这是否正确。它创建一个包含所有选定选项的对象。

'change [name="specialisation"]': function ( event, template ) {

    $(document).ready(function(){

        var specialisation = $('input[name="specialisation"]:checked').map(function(){

            return $(this).val();

        });

        var specialisationListArray = specialisation.get();
        template.candidateListFilter.set( specialisationListArray );
    });
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2021-04-19
    相关资源
    最近更新 更多