0

I want to assign an URL in a function everytime a checkbox is checked. But I would also like the URL to be reassigned its initial value when the checkBox is unchecked. I was able to create the code below from the following thread, but the URL is not reassigned when I uncheck the box. Sorry I am new to KnockoutJS and to JavaScript in general.

HTML

   <input type="checkbox" name="myCheckBox" data-bind="checked:isChecked, click: setUrl">Search Supplier<br>

JS

  searchShippingCodesUrl = '/Parteners/Search';
...
...
ischecked: ko.observable(false),
        setUrl: function () {
                searchShippingCodesUrl = '/Suppliers/Search';
                return true;            
        },

Thank you for your time.

Community
  • 1
  • 1
Yanov Adamsky
  • 122
  • 2
  • 9
  • the click event would fire when checking or unchecking, and your setUrl function doesn't make any check against isChecked to determine what the url should be – dfperry Jan 22 '16 at 16:45

2 Answers2

3

Only use the click binding on a checkbox if you need to differentiate whether the checkbox changed state by click vs. by internal setting. The checked binding captures the state of the view for you, so you can then work with it in your viewmodel. To take action when it changes, you subscribe to the observable (I borrow the variables here from dfperry's example):

ischecked.subscribe(function (newValue) {
    searchShippingCodesUrl = newValue ? supplierSearch : partnerSearch;
});
Roy J
  • 42,522
  • 10
  • 78
  • 102
1

You need to check against isChecked in your setUrl function to get that toggle effect:

var partnerSearch = '/Partners/Search',
    supplierSearch = '/Suppliers/Search';

searchShippingCodesUrl = partnerSearch;

...

ischecked: ko.observable(false),
setUrl: function () {

  searchShippingCodesUrl = (ischecked() ? supplierSearch : partnerSearch);
  return true;            
}
dfperry
  • 2,258
  • 1
  • 14
  • 22