Customize the value of an HTML element element interactively using Meteor

I want to set the value of an HTML <select> element reactively without changing the various parameters for the element. I found a solution, but it is not elegant.

To test, create a Meteor application with barebone with create meteor select and change the contents of the select.html and select.js files to the following:

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") } } } 

Now run the application. In the browser console, you can change the value of the category Session variable:

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

However, the selection item will not be updated until you change the label:

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

The selection element is now updated, and any subsequent change to the category Session variable will also update the select element.

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

Is it possible to achieve the same effect directly without using this awkward workaround?

+5
source share
2 answers

Yes. You can do it as follows:

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

And helpers that look something like this:

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

Something like this might be better:

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

And then you can use this in helpers to decide what is selected and what is not.

Another option is to simply use standard jQuery to change the select box. Something like that:

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

Or this answer is SO .

+6
source

If you want the selection to be set dynamically, I usually use a descriptor helper like this

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

then in html

 <select class="browser-default" id="selectedService" name="jobtype"> <option id="zero" value="{{filler 'type'}}">{{filler 'type'}}</option> 
0
source

All Articles