简体   繁体   中英

Knockout radio checked binding

I have some radio buttons that use knockout checked bindings. After making the initial submission with the radios, the template gets the value of the radio and the correct radio button is checked . The problem is when I reload the page the previous submission no longer has any checked radios .

Here's the code:

<input data-bind= "checked: Type, required:Type type="radio" value="1" />
<label>Allowed</label>
<input data-bind= "checked: Type, required: Type, type="radio" value="2" />
<label>Charge</label>

In looking at the knockout context plugin with Chrome it shows that the type is set to the original submissions value, however they are still not checked on reload. 在此处输入图片说明

If you want to retain value on a page reload you may want to use local storage.

here is a fiddle when you reload the page it will retain your last checked radio button.

https://jsfiddle.net/0o89pmju/50/

html

<input type="radio" data-bind="checked: Type"  value="1" name="myradio" />
<label>Allowed</label>
<input type="radio" data-bind="checked: Type"  value="2" name="myradio" />
<label>Charge</label>

<p>
  the value is: <label data-bind="text: Type"></label>
</p>

javascript

function Model() {
  var self = this;
  this.Type = ko.observable(localStorage.getItem("Type"))
}
var vm = new Model()
$( document ).ready(function() {
    ko.applyBindings(vm);
    vm.Type.subscribe(function(newValue) {
       localStorage.setItem("Type", newValue);
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM