如何在使用Meteor时选择HTML中的多个复选框?

4

我需要了解如何使用Meteor选择HTML中的多个复选框。我做了一个示例,在这个示例中选择了多个复选框,但不知道如何获取所选数据并将其存储在数组中。以下是示例代码,请给我建议:

将详细信息存储在数组中,例如:arrayname = Bike,car,Computer(这些是所选项目)

HTML代码:

<form id="cb-form" action="action">
<input type="checkbox" name="owns" value="Bike">Bike<br/>
<input type="checkbox" name="owns" value="Car">car<br/>
<input type="checkbox" name="owns" value="Refridgerator">Refridgerator<br/>
<input type="checkbox" name="owns" value="Mobile">Mobile<br/>
<input type="checkbox" name="owns" value="Tablet">Tablet<br/>
<input type="checkbox" name="owns" value="Computer">Computer<br/>
<input type="submit"  value="send" />
</form>

JS 代码:

Template.login.events

  ({

    'submit #cb-form' : function (e,t)

    {

      // template data, if any, is available in 'this'

      if (typeof console !== 'undefined')

        console.log("You pressed LOGIN Button");

        e.preventDefault();

       //retrieve the input field values

         //here write get multiple check boxes data logic same as above scenario
     }

  });
1个回答

10

HTML:

<template name="login">
  <form id="cb-form" action="action">
   <input type="checkbox" name="owns" value="Bike">Bike<br/>
   <input type="checkbox" name="owns" value="Car">car<br/>
   <input type="checkbox" name="owns" value="Refridgerator">Refridgerator<br/>
   <input type="checkbox" name="owns" value="Mobile">Mobile<br/>
   <input type="checkbox" name="owns" value="Tablet">Tablet<br/>
   <input type="checkbox" name="owns" value="Computer">Computer<br/>
   <input type="submit"  value="send" />
 </form>  
</template>

JS:

Template.login.events({
 'submit #cb-form' : function (event, template) {
   event.preventDefault();

   var selected = template.findAll( "input[type=checkbox]:checked");

   var array = _.map(selected, function(item) {
     return item.defaultValue;
   });

   console.log(array);

 }
});

如果选择了Car和Refridge,这将输出["Car", "Refridgerator"]。这只是使用underscore的简单用法。查看underscore文档以获取进一步阅读。


1
我知道这很老了,但如果您没有安装下划线,您可以使用Array.map。以上内容将是var array = selected.map(function(item){ return item.value})。 - Kilmazing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接