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/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s