Binding true / false to radio buttons in Knockout JS

后端 未结 8 2163
悲哀的现实
悲哀的现实 2020-11-30 22:09

In my view model I have a IsMale value that has the value true or false.

In my UI I wish to bind it to the following radio buttons:

相关标签:
8条回答
  • 2020-11-30 22:17

    Why not simply true and false instead of 1 and 0?

     <label>Male
        <input type="radio" name="IsMale" value="true" data-bind="checked:IsMale"/>
     </label> 
     <label>Female
        <input type="radio" name="IsMale" value="false" data-bind="checked:IsMale"/>
     </label>
    
    0 讨论(0)
  • 2020-11-30 22:24

    One option is to use a writeable computed observable.

    In this case, I think that a nice option is to make the writeable computed observable a "sub-observable" of your IsMale observable. Your view model would look like:

    var ViewModel = function() {
       this.IsMale = ko.observable(true);
    
       this.IsMale.ForEditing = ko.computed({
            read: function() {
                return this.IsMale().toString();  
            },
            write: function(newValue) {
                 this.IsMale(newValue === "true");
            },
            owner: this        
        });          
    };
    

    You would bind it in your UI like:

    <label>Male
       <input type="radio" name="IsMale" value="true" data-bind="checked:IsMale.ForEditing"/>
    </label> 
    <label>Female
       <input type="radio" name="IsMale" value="false" data-bind="checked:IsMale.ForEditing"/>
    </label>
    

    Sample: http://jsfiddle.net/rniemeyer/Pjdse/

    0 讨论(0)
  • 2020-11-30 22:25

    You can also use an extender so it's easy to reuse them for more observables:

    ko.extenders.boolForEditing = function (target, allowNull) {
        var result = ko.computed({
            read: function () {
                var current = target();
                var newValue = null;
                if (current === undefined || current === null || current === '') {
                    if (!allowNull) {
                        newValue = 'false';
                    }
                } else {
                    newValue = current ? 'true' : 'false';
                }
                return newValue;
            },
            write: function (newValue) {
                var current = target();
                var valueToWrite = null;
                if (newValue === undefined || newValue === null || newValue === '') {
                    if (!allowNull) {
                        valueToWrite = false;
                    }
                } else {
                    valueToWrite = newValue === 'true';
                }
                // only write if it changed
                if (valueToWrite !== current) {
                    target(valueToWrite);
                } else {
                    if (newValue !== current) {
                        target.notifySubscribers(valueToWrite);
                    }
                }
            }
        }).extend({
            notify: 'always'
        });
    
        result(target());
    
        return result;
    };
    

    Then use it like this:

    this.IsMale.forEditing = this.IsMale.extend({boolForEditing: true});
    

    The parameter provided to boolForEditing indicates whether the value may be null.

    See http://jsfiddle.net/G8qs9/1/

    0 讨论(0)
  • 2020-11-30 22:30

    I know this is an old thread, but I was having the same problem and found out a much better solution that was probably added to knockout after this question was officially answered, so I'll just leave it for people with the same problem.

    Currently there is no need for extenders, custom binding handlers or computeds. Just provide a "checkedValue" option, it will use that instead of the html 'value' attribute, and with that you can pass any javascript value.

    <input type="radio" name="a" data-bind="checked:IsChecked, checkedValue: true"/>
    <input type="radio" name="a" data-bind="checked:IsChecked, checkedValue: false"/>
    

    Or:

    <input type="radio" name="b" data-bind="checked:Quantity, checkedValue: 1"/>
    <input type="radio" name="b" data-bind="checked:Quantity, checkedValue: 2"/>
    <input type="radio" name="b" data-bind="checked:Quantity, checkedValue: 3"/>
    
    0 讨论(0)
  • 2020-11-30 22:32

    Once you figure out that the initial match for the radio button wants to match only a string and wants to set the value to a string, it is simply a matter of converting your initial value to string. I had to fight this with Int values.

    After you have setup your observables, convert the value to string and KO will do its magic from there. If you are mapping with individual lines, do the conversion in those lines.

    In the example code, I'm using Json to map the whole Model in a single command. Then letting Razor insert the value between the quotes for the conversion.

    script type="text/javascript">
        KoSetup.ViewModel = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));
        KoSetup.ViewModel.ManifestEntered("@Model.ManifestEntered");       //Bool
        KoSetup.ViewModel.OrderStatusID("@Model.OrderStatusID");           //Int
    </script>
    

    I use a "Dump it all to the screen" at the bottom of my web page during development.

    <h4>Debug</h4>
    <pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
    

    Here are the data values, Before

    "OrderStatusID": 6,
    "ManifestEntered": true,
    

    and, After

    "OrderStatusID": "6",
    "ManifestEntered": "True",
    

    In my project, I didn't need to convert Bools, because I'm able to use a checkbox that doesn't have the same frustration.

    0 讨论(0)
  • 2020-11-30 22:33

    This works for me:

    http://jsfiddle.net/zrBuL/291/

    <label>Male
       <input type="radio" name="IsMale" value="1" data-bind="checked:IsMale"/>
    </label> 
    <label>Female
       <input type="radio" name="IsMale" value="0" data-bind="checked:IsMale"/>
    </label>
    
    0 讨论(0)
提交回复
热议问题