【问题标题】:Pass checkbox value IF the checkbox is checked如果复选框被选中,则传递复选框值
【发布时间】:2016-03-04 13:28:54
【问题描述】:

我有一个如下所示的复选框列表:

<div class="checkbox">
<label><input type="checkbox" value="west" name="west" id="west" checked="{{isChecked}}">West</label>
</div>
<div class="checkbox">
<label><input type="checkbox"  checked="{{isChecked}}" name="airport" id="airport" value="airport">Airport</label>
</div>
<div class="checkbox">
<label><input type="checkbox"  checked="{{isChecked}}" name="north" id="north" value="north">North</label>
</div>

我设法将每个复选框的状态作为布尔值传递给集合,如下所示:

var eventLocation = [
event.target.west.checked,
event.target.airport.checked,
]

但是,我只想传递选中复选框的值。我知道我可以使用event.target.west.value 传递复选框的值,但是要仅获取选中的复选框,我必须编写许多条件,这不能很好地扩展。有更好的方法吗?

谢谢!

【问题讨论】:

    标签: javascript arrays meteor checkbox meteor-helper


    【解决方案1】:

    您可以通过以下方式快速收集所有选中的复选框:

    var checked = $("input:checked");
    

    这将返回一个数组,您可以循环访问该数组以获取 id、值或名称。

    checked.forEach(function(c){
      console.log('input id: '+c.id+' name: '+c.name+' value: '+c.val+' is checked!');
    });
    

    【讨论】:

    • 太棒了 - 非常感谢!我实际上实现了一些非常相似的东西:$('.event-location-form input[type=checkbox]').each(function () { if(this.checked){ eventLocation.push($(this).val()); } });
    • 您可以在没有if (this.checked) 的情况下执行此操作! $('.event-location-form input[type=checkbox]:checked').each(function () { eventLocation.push($(this).val()); });
    猜你喜欢
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    相关资源
    最近更新 更多