2015-09-20 6 views
5

要素のさまざまなオプションを変更せずに、HTML <select>要素の値を反応的に設定したいとします。私は解決策を見つけましたが、それは優雅ではありません。 、テストcreate meteor selectとベアボーン流星アプリを作成し、次へselect.htmlの内容とselect.jsファイルを変更するにはMeteorと反応して選択HTML要素の値を設定する

select.html

<body> 
    {{> select}} 
</body> 

<template name="select"> 
    <label for="select">{{category}}</label> 

    <select id="select"> 
    <option value='' disabled selected style='display:none;'>Select...</option> 
    <option value="Animal">Animal</option> 
    <option value="Vegetable">Vegetable</option> 
    <option value="Mineral">Mineral</option> 
    </select> 
</template> 

select.js

if (Meteor.isClient) { 
    Session.set("category", "") 
    Session.set("label", "Category") 

    Template.select.onRendered(function() { 
    setSelectValue() 
    }) 

    Template.select.helpers({ 
    category: function() { 
     setSelectValue() 
     return Session.get("label") 
    } 
    }); 

    function setSelectValue() { 
    var select = $("#select")[0] 
    if (select) { 
     select.value = Session.get("category") 
    } 
    } 
} 

アプリを起動します。ブラウザのコンソールでは、categoryセッション変数の値を変更することができます。

Session.set("category", "Animal") 

ラベルを変更するまでしかし、select要素は更新されません。

Session.set("label", "category") // was "Category' 

今select要素の更新を、それ以降の変更はセッション変数categoryもselect要素を更新します。

Session.set("category", "Vegetable") // Now the select element updates 

この不器用な回避策を使用せずに、同じ効果を直接達成することはできますか?

答えて

6

はい。

Template.select.helpers({ 
    animalSelected: function() { 
     return (someCondition === true) ? 'selected' : ''; 
    }, 
    vegetableSelected: function() { 
     return (someOtherCondition) ? 'selected' : ''; 
    } 
    }); 

がより良い方法はしかし、このようなものかもしれません:このような何かに見える

<select id="select"> 
    <option value="Animal" {{animalSelected}}>Animal</option> 
    <option value="Vegetable" {{vegetableSelected}}>Vegetable</option> 
    <option value="Mineral" {{mineralSelected}}>Mineral</option> 
    </select> 

そしてヘルパー:次のようにあなたはそれを行うことができます

<select id="select"> 
    {{#each options}} 
     <option value="{{value}}" {{selected}}>{{label}}</option> 
    {{/each}} 
    </select> 

をそれから、あなたのことができヘルパーでthisを使用して、選択されているものとされていないものを決定してください。

もう1つの選択肢は、標準jQueryを使用して選択ボックスを変更することです。このようなもの:

$('[name=options]').val(3); 

またはthis SO answerです。

0

あなたが選択を動的に設定したい場合、私は普通のhtml

<select class="browser-default" id="selectedService" name="jobtype"> 
    <option id="zero" value="{{filler 'type'}}">{{filler 'type'}}</option> 
に、この

Template.newtask.helpers({ 
    filler: function(element){ 
    return Session.get(element); 
    } 
}); 

のようなハンドルバーヘルパーを使います

関連する問題