Dynamic Toggle Functionality – Knockout and JavaScript

Last week as part of an interface redesign, I had to revamp a user search screen. One of the first functionality which I had to incorporate was a dynamic toggle feature between a dropdown list and checkbox using Knockout.

Use Case Scenario

The UI has a drop-down with 2 values – Invoice Number and Subscriber Code.

  • If the user selects ‘Invoice Number’ in the drop-down, then a text-box is displayed where the user can type an invoice number.
  • If the user selects ‘Subscriber Code’ in the drop-down, then a drop-down is displayed with pre-populated fields for the user to choose from.

I started playing around in JSFiddle and came up with different prototypes to achieve this functionality using plain Javascript and then using Knockout.

The below code is the functionality implementation using pure Javascript —

Knockout is a powerful Javascript library which provides a simple two-way data binding mechanism between your data model and UI- which means that any changes to data model is automatically reflected in the UI and similarly any changes to the UI  are automatically reflected in the data model.

The below code is the implementation using KnockOut and you can see how it simplifies Javascript using declarative bindings —

You can check out the below JSFiddle I created for this functionality —

https://jsfiddle.net/SamirBehara/9gt70p4w/

https://jsfiddle.net/SamirBehara/6kxevfdn/



Categories: C#, JavaScript, KnockOut

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: