Bunjip
Bunjip

Reputation: 297

Meteor 1.0 How to realize this UI behaviour plus DOM manipulation in general?

I want to make a UI component that aims to give the user a simple way to select (predefined) keywords (such as 'breakfast', 'dinner', ...) via checkboxes. There's a text field that displays the keywords selected (comma separated) or enables the user to manually add (new) keywords. If the user unchecks a 'keyword', the corresponding entry shall be removed from the text field. If the user exits from the current screen and returns later, the previously selected keywords should still be checked.

So far, I have the template:

<template name="mealTypeControls">
  <input type="text" id="meal-type-display" class="multi-keyword-selection--display form-control" value="{{selectedTypes}}" placeholder="{{selectedTypes}}">
  <ul class="multi-keyword-selection--list">
    {{#each mealTypes}}
    <li class="multi-keyword-selection--item">
        <input type="checkbox" class="meal-type-item" id="{{id}}" value="{{id}}">
        <label for="{{id}}">{{name}}</label>
    </li>
    {{/each}}
  </ul>
</template>

And the template manager

var mealTypeArray = [
{id: 'breakfast', name: 'Breakfast'},
{id: 'lunch', name: 'Lunch'},
{id: 'tea', name: 'Tea'},
{id: 'snack', name: 'Snack'},
{id: 'dinner', name: 'Dinner'}
];
Template.mealTypeControls.helpers({
  mealTypes: mealTypeArray,
  selectedTypes: function(){
      return Session.get('selectedTypesString');
  }
});
Template.mealTypeControls.events({
  'change .meal-type-item': function(event, template){
      if ($(event.target).is(':checked')){
          var selectedType = event.target.value;
          Session.set(
            'selectedTypesString', template.$('#meal-type-display').val() + ', ' + selectedType
          );
      }
  }
});

As I'm new to Meteor, my questions are if the general approach appears to make some sense? How can I realise the 'remove keyword from display field on uncheck' feature properly? How can the latest state of the component be saved until the next time the whole view is created?

How to actually perform DOM manipulation and form data transfer with Meteor? When to use jQuery or DOM manipulation via Template object? I have kind of hard time to use $(event.target).is(':checked') in an if statement while a line later I have to use event.target.value to access the checkbox value and I'm quite confused regarding DOM manipulation in Meteor.

Your hints, help and best practises are much appreciated. Cheers, Bunjip

Upvotes: 0

Views: 147

Answers (1)

Brylie Christopher Oxley
Brylie Christopher Oxley

Reputation: 1862

Consider the Autoform package. You can define a SimpleSchema field with allowed values, and tell Autoform to render the field as a select option group. If I recall correctly, Autoform even has an option to automatically update the data when it changes.

Upvotes: 0

Related Questions