简体   繁体   中英

How to add selected attribute to dropdown option tag in Meteor Blaze?

HTML

<select id="article-weight">
    {{#each weightValues}}
        <option value="{{this}}">{{this}}</option>
    {{/each}}
</select>

JS

Template.articleSingle.helpers({
    weightValues: function(){
        return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    }
)};

Template.articleSingle.events({
    'change #article-weight': function (event, template) {
        weight = parseInt( $(event.currentTarget).val() );
        Meteor.call('updateArticle', template.data._id, {
            weight: weight
        });
    }
)};

I want something like this

{{#each weightValues}}
    <option {{#if weight==this}}selected{{/if}} value="{{this}}">{{this}}</option>
{{/each}}

But it's certainly not possible to compare a variable inside an if block of Blaze.
Any idea how can achieve my desired result?

Template.articleSingle.helpers({
    weightValues: function(){
        return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    },
    isSelected:function(comparison){
        return comparison === this;
    },
    yourComparison:function(){
        return 3;
    },
)};

{{#each weightValues}}
    {{#if isSelected yourComparison}}
        <option selected='true' value="{{this}}">{{this}}</option>
    {{else}}
       <option value="{{this}}">{{this}}</option>
    {{/if}}
{{/each}}

try this

Template.articleSingle.helpers({
    weightValues(){
       return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   },
   weight(){
      return 2
   },
)};

<select id="select">
  {{#each weightValues}}
        <option {{#if $eq this weight}} selected="selected" {{/if}} value="{{this}}">{{this}}</option>
   {{/each}}
</select>

or you can do with javaScript

 $('#select option[value="2"]').attr('selected', 'selected');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM