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



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

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

  1. 查找输入的值字段(例如:"Americanan")是否在数组中
  2. 如果值包含在数组中,则返回"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}}

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

由于您无论如何都在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进行检查,但这意味着您在模板中迭代的对象必须包括所有烹饪类型,而不仅仅是已检查的烹饪类型。在某个地方,你需要一个所有烹饪类型的集合或数组来迭代。

最新更新