Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set radio button checked using knockout.js?

I have two radio buttons.

<td>
    <div style="display: inline; margin-right: 10px">
         <input type="radio" name="USGlobalUser" data-bind:"checked:IsGlobal/>US
    </div>
    <div style="display: inline">
         <input type="radio" name="USGlobalUser" data-bind:"checked:IsGlobal"/>Global
    </div>
</td>

I am populating my model like this

QuestionnaireModel = function (data) {
  self.IsGlobal = ko.protectedObservable(data ? data.IsGlobal : false);
}

The value is coming from DB perfectly and its getting populated in self.IsGlobal as true/false. Based upon this true/false, I want to set my radio button checked.

like image 819
NayeemKhan Avatar asked May 28 '13 04:05

NayeemKhan


1 Answers

The checked binding works differently for radio buttons:

For radio buttons, KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute. So, your parameter value should be a string.

So your IsGlobal should hold a string and you need to have the same string as the value of the radio buttons:

<input type="radio" name="USGlobalUser" 
       data-bind="checked: IsGlobalCheckbox" value="false" />US
<input type="radio" name="USGlobalUser" 
       data-bind="checked: IsGlobalCheckbox" value="true" />Global

And in your viewmodel:

self.IsGlobal = ko.observable(data ? data.IsGlobal + "" : "false");

If you want to keep the IsGlobal to store a boolean value you need to create a new computed property for the radio button which does the conversion:

self.IsGlobalCheckbox = ko.computed({
    read: function() {
        return self.IsGlobal() + "";
    },
    write: function (v) {
        if (v == "true") self.IsGlobal(true)
        else self.IsGlobal(false)
    }
}); 

Demo JSFIddle.

And by the way as Tomas noted your binding systax is broken in your sample.

like image 183
nemesv Avatar answered Oct 15 '22 10:10

nemesv