Meteor select element setting selected value

自古美人都是妖i 提交于 2019-12-21 23:23:36

问题


Inside my Meteor js app I have the select element shown below inside a form where I need to check and display selected value upon loading the form, I tried researching on how to do so in Meteor but couldn't find any info, so can someone please tell me how I can check which of the options is selected to make this option as a selected option? Thanks for your help

            <select name="memberType" class="form-control">
              <option value="Member">Member</option>
              <option value="Admin">Admin</option>
              <option value="Visitor">Visitor</option>                
            </select>           

回答1:


You can use these universal helpers :

JS

Template.registerHelper("checkedIf",function(value){
  return value?"checked":"";
});

Template.registerHelper("selectedIfEquals",function(left,right){
  return left==right?"selected":"";
});

HTML

<template name="myTemplate">
  <input type="checkbox" {{checkedIf checked}}>
  <select>
    {{#each options}}
      <option value={{value}} {{selectedIfEquals value ../valueCheckedAgainst}}>
        {{text}}
      </option>
    {{/each}}
  </select>  
</template>

They are intended to be used with correctly set template data contexts :

Template.myTemplate.helpers({
  checked:function(){
    // return a Session variable or a value from a collection
    // dummy value
    return false;
  },
  options:function(){
    return [{
      value:"value1",
      text:"First value"
    },{
      value:"value2",
      text:"Second value"
    },{
      value:"value3",
      text:"Third value"
    }];
  },
  valueCheckedAgainst(){
    // return a Session variable or a value from a collection
    // dummy value
    return "value2";
  }
});

Note the use of the ../parentContext syntax to access valueCheckedAgainst from parent data context inside the {{#each}} block.



来源:https://stackoverflow.com/questions/26701935/meteor-select-element-setting-selected-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!