0
votes

Hi I have started using Knockout because it is for my purpose easier then jQuery. I have used jQuery before but that made my code almost unreadable.

I have this javascript viewmodel

function ovm() {
    this.delStreet = ko.observable("");
    this.deliveryNotSameAsInvoice = ko.observable(false);
    this.invStreet = ko.observable("");
}
ko.applyBindings(new ovm());

and this HTML:

<label><input type="checkbox" data-bind="checked: deliveryNotSameAsInvoice" />if your invoice address is not the same as delivery</label>
<div id="delivery">
    <input type="text" placeholder="Street" 
        data-bind="value: delStreet, valueUpdate:'afterkeydown'" />
</div>
<div id="invoice" data-bind="visible: deliveryNotSameAsInvoice">
    <input type="text" placeholder="Street" 
        data-bind="value: invStreet, valueUpdate:'afterkeydown'" />
</div>
<hr/>
Delivery street: <span data-bind="text: delStreet"></span><br/>
Invoice street: <span data-bind="text: invStreet"></span><br/>

The thing is that I want invStreet to have the value of delStreet as long as the checkbox is unchecked. I have a working jsFiddle here and have found this SO question about conditional binding but I cannot find a good code sample. In jquery I had to bind keyup events to each textbox and depending on if the checkbox was checked, I had to set several fields. It was a lot of work. Especially with a larger 'view model'

1
seems like some one is having fun with Knockout.js :) - user372551

1 Answers

1
votes

use a computed observable for invStreet.. like this

function ovm() {
     var self = this;
     this.delStreet = ko.observable("");
     this.deliveryNotSameAsInvoice = ko.observable(false);
     this.invStreet = ko.observable("");
     var invStreetCheck = ko.computed(function(){
         var checked = self.deliveryNotSameAsInvoice(),
             delStreet = self.delStreet();
         if(!checked)
             return self.invStreet(delStreet);
         return self.invStreet();
     });
 }

 ko.applyBindings(new ovm());

Now when the checked binding is true it will return "" else it will contain delStreet. value.