radio button checked binding html5, durandal

2019-08-14 22:50发布

问题:

even that I see very many similar questions in this site, no one of them answer to my question. So pleas, don't be angry with me that I discuss this subject again. I work in durandal project, I have html pages with javascript files behind. I have two radio button in one of the pages. I want their "checked" attribute to be binding to a variable in the view-model behind. It is looked simple... but it is not! I try two ways, any one of them didn't succeed:

first-way: in the html:

                             <input type="radio"
                                    name="radSearchBy"
                                    id="byNo"
                                    data-bind:"checked:isId" />

          in javascript:
                         isId: ko.observable(true)      

second-way: in the html:

          in javascript:
                         isId: ko.observable("checked")        

I know what is the problem. even if I simply write

                           <input type="radio"
                                    name="radSearchBy"
                                    id="byNo"
                                    data-bind:"checked:true" />  

or:

                     <input type="radio"
                                    name="radSearchBy"
                                    id="byNo"
                                    checked="checked" />     

it doesn't work. only whem I write:

                     <input type="radio"
                                    name="radSearchBy"
                                    id="byNo"
                                    **checked** />    

yes, the "checked" word without anything follow- it works well.

but it is problem, becouse how can I do it *binding?*

please help me as quick as you can.

回答1:

Unfortunately, the answer is a bit complicated. Radio buttons match the value of your observable to the value attribute of the radio button. In the boolean case, it is impossible to handle simply because HTML will return 'true' or 'false' as strings, not as booleans.

The solution requires AFAIK computed observables:

HTML

<input type="radio"
    name="radSearchBy"
    value="true"
    data-bind="checked: value" />True
<input type="radio"
    name="radSearchBy"
    value="false"
    data-bind="checked: value" />False

JavaScript

radSearchBy = ko.observable(true);
value = ko.computed({
    read: function() { return radSearchBy.toString(); },
    write: function(val) { radSearchBy(val === 'true'); }
});