【问题标题】:JS/Meteor: Returning 'checked' if string is found in arrayJS/Meteor:如果在数组中找到字符串,则返回“已检查”
【发布时间】:2016-03-06 03:51:38
【问题描述】:

我创建了一个表单,如果选中某个选项的复选框,则在提交表单时,它会将选中输入的值传递给字符串数组(cuisineType,在venueAttributes 子模式中)。

我正在尝试构建等效的更新表单,我需要:

  1. 查找输入的值字段(例如:'american')是否在数组中。
  2. 如果值包含在数组中,则返回“已选中”(或将复选框标记为选中)。

这是我到目前为止所拥有的,但不确定我是否走在正确的道路上。我应该在下划线中使用._find() 吗?

<label>Type of Cuisine</label>
{{#each venueAttributes.cuisineType}}
  <div class="form-group" id="cuisineForm">     
    <div class="checkbox">
      <label><input type="checkbox" checked="???" name="american" id="american" value="american">American</label>
    </div>
    <div class="checkbox">
      <label><input type="checkbox" checked="???" name="french" id="french" value="french">French</label>
    </div>
  </div>
{{/each}}

感谢您提供的任何见解! 丹

【问题讨论】:

    标签: javascript arrays meteor meteor-blaze


    【解决方案1】:

    由于您正在迭代venueAttributes.cuisineType,因此您只需要一个子项:

    <template name="cuisines">
    <label>Type of Cuisine</label>
    {{#each venueAttributes.cuisineType}}
      <div class="form-group" id="cuisineForm">     
        <div class="checkbox">
          <label><input type="checkbox" checked={{isChecked}} name={{this}}
            id={{this}} value={{this}}>{{this}}</label>
        </div>
      </div>
    </div>
    {{/each}}
    </template>
    

    现在您需要一个 isChecked 助手来决定是否检查给定项目。

    Template.cuisines.helpers({
      isChecked: function(){
        return ( checkedCuisines.indexOf(this) > -1 );
      }
    });
    

    但是,问题!

    你的问题是:

    将检查输入的值传递给字符串数组 (cuisineType,在venueAttributes 子模式中)。

    但是你在这个模板中循环了venueAttributes.cuisineType,所以根据定义,数组只包含以前检查过的项目。我使用不同的数组 checkedCuisines 进行检查,但这意味着您在模板中迭代的对象必须包括所有美食类型,而不仅仅是已检查的那些。在某个地方,您需要对所有美食类型的集合或数组进行迭代。

    【讨论】:

    • 谢谢米歇尔!我偶然发现了一个以这种方式进行的教程,但我想避免创建另一个比较数组/集合,因为我将拥有有限数量的美食类型(这意味着我必须将其维护为好吧)。我打算仍然为每个选项(美式、法式等)保留 HTML 中所有可能的输入元素,并使用检查值(或我作为助手参数传递的硬编码字符串)存在于数组中(使用 find()?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多