Using knockout.js and MVVM with RadioButtons

In the example below, radio buttons selection list is created by binding to a list in the view model. I show how to bind to both the selected radio button’s value and name. I also show how to disable a button unless the radio button is selected.

<!-- Step 1 - Create the HTML File or the View -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="scripts/knockout-2.2.1.js"></script>
    
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript" >
        $(document).ready(function(){

			<!-- Step 4 - Add a RadioButtonModel -->
            function RadioButtonModel(inText, inValue, inGroupName) {
                this.text = inText;
				this.value = inValue;
				this.name = inGroupName;
            }

			<!-- Step 5 - Create ViewModel -->
            function SurveyViewModel() {
                var self = this;
                
				<!-- Step 7 - Create an observable list -->
                this.list = ko.observableArray([
                    new RadioButtonModel("Good", 10, "Q1"),
                    new RadioButtonModel("Average", 5, "Q1"),
                    new RadioButtonModel("Poor", 1, "Q1")
                ]);
				
				<!-- Step 8 - Create a selected item -->
				this.selected = ko.observable(0);
				
				<!-- Step 9 - (Optional) Create a computed value to get the selected text -->
				this.selectedtext = ko.computed(function() {
					var text = "";
				    ko.utils.arrayForEach(this.list(), function(item) {
						var selectedItem = self.selected();
						if (selectedItem == item.value)
							text = item.text;
					});
					return text;
				}, this);
				
				
				<!-- Step 10 - Create a computed value to require a selection before submitting -->
			    this.canClick = ko.computed( function() {
                    return this.selectedtext() != "";
                }, this);
                
            }
            
            <!-- Step 10 - Create a computed value to require a selection before submitting -->    
            ko.applyBindings(new SurveyViewModel());
        });
    </script>
</head>
<body>
    <!-- Step 11 - Create a div containing the html for one radio button and bind to foreach: list -->
    <div data-bind="foreach: list">
        <input type="radio" data-bind="attr: {name: name}, value: value, checked: $root.selected" /><span data-bind="text: text"></span>
    </div>

    <!-- Step 12 - Add html elements to see other properties -->
    <p data-bind="text: selected"></p>
    <p data-bind="text: selectedtext"></p>
    
    <!-- Step 13 - Add a button and bind its enable state -->
    <button type="submit" id="btnSubmit" data-bind="enable: canClick">Submit</button>

</body>
</html>

Hope this helps you.

2 Comments

  1. Toni says:

    Hello! This is great help!

    I got one problem though. I need to create a survey list with different answer alternatives on each question. Answer alternatives I want to show as radiobutton list. How can I bind these dynamically and catch the selected values in the end?

    Hope you can help

    Toni

    • Rhyous says:

      You just have to code it up between your ViewModel and data.

      So imaging you have question 1 and question 2. Each have their own RadioButtonViewModel (two of them, vm1 and vm2).

      Add a javascript method that subscribes to the selected observable on vm1. Then when you change an the answer, your method runs and you can update the vm2 list.

Leave a Reply

How to post code in comments?