JS/Meteor:如果在数组中找到字符串,则返回 'checked'

JS/Meteor: Returning 'checked' if string is found in array

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

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

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

这是我目前所掌握的,但不确定我是否走在正确的道路上。我应该在下划线中使用 ._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}}

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

既然你要遍历 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 );
  }
});

但是,问题!

您的问题是:

passes the value of checked inputs to an array of strings (cuisineType, within the venueAttributes subschema).

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