Justin Helgerson
Justin Helgerson

Reputation: 25521

Show different form fields based on selection

jsFiddle

I am using Knockout.js in various parts of my project. I'm looking for advice on the best way to achieve adding HTML content to a form based on what the user has selected.

I put together a jsFiddle that I believe makes it clear what I'm trying to accomplish.

If a user selects options 1 or 2, the HTML markup from data-configuration="1,2" is added to the form. If a user selects option 3, then the HTML markup from data-configuration="3" is added to the form.

I have a few ideas for how to do this (hooking into the change event of the select list), but, I was wondering if anybody had a better "knockout" way of accomplishing this.

Upvotes: 1

Views: 120

Answers (2)

WiredPrairie
WiredPrairie

Reputation: 59763

One other idea would be to create a binding handler as it gives you more control over the behavior.

http://jsfiddle.net/DRP3d/

It requires jQuery as written (but only just to make the code more concise).

Essentially, it just looks at the bound value, looks at the attribute you used in your html (data-configuration) and then hides or shows a given element based on the comparison of value to configuration.

ko.bindingHandlers.showtype = {
  update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
      var $element = $(element);
      var config = $(element).attr('data-configuration');
      var value = ko.utils.unwrapObservable(valueAccessor());
      config = config.split(',');

      var found = false;
      for(var i=0, len=config.length; i < len; i++) {
          if (value == config[i]) {
              found = true;
              break;
          }  
      }
      if (found) { $element.show(); } else { $element.hide(); } 
  }      
};

Upvotes: 1

Paul Manzotti
Paul Manzotti

Reputation: 5147

Generally, I'd be looking to set the css class on each section based on the dropdown value, somthing like:

<div data-bind="css: { hide: TypeId() == '' || TypeId() != 3 }">

I've updated the jsFiddle for you too.

Alternatively, use the if-binding with the same logic I used above, and this will actually take the hidden elements out of the DOM.

Upvotes: 1

Related Questions