I am pretty new to knockout and need some help. I have form which will be loaded when I click on NEW button and it will be also loaded from some listing page when I click on user name in listing page(dataTable).
What I need is looks pretty basic and straight forward.
Scenario 1 : When I am coming from NEW button I need to fill all fields and then I have to save(button) which will in enabled state where I am also having NEXT STAGE BUTTON which is disabled But on successful save it need to get enabled and so I can go to next stage/page.
Scenario 2 : Well this is were I am facing trouble to sort things. When I come from some listing page when I click on username link The data will be autofilled in form and now I have to make my NEXT STAGE button enable upfront on load just because it is already a saved form.
What I tried so far:
<button id="btnSave" class="btn" data-bind="click:$data.save">SAVE</button>
<input type ="button" id="nextstage" data-bind="click:$root.nextstage,enable:false" value="NEXT STAGE"/>
I am also trying to achieve using IF condition in data-bind where I have absolutely no clue how to.
My idea : In data-bind I will enable/disable NEXTSTAGE based on the field on my form like example if I am having something like this
<input type="text" id="txtComepitors" data-bind="value:$data.Competitors"/>
On my page load if the textbox is empty I will DISABLE if it is not I will enable. So I just need if condition to enable/disable nextstage in data-bind.
That's all I have and thought of it sadly lacks proper implementation.
It's really hard to get from your question exactly what you are asking, but the cleanest way to do this would be with a computed observable.
So somewhere in your view model you'd have something like this:
self.canSave = ko.computed(function() {
// test conditions for saving here (i.e. whether all the fields have values)
// and return true if you can save
// for example:
return self.someProperty() && self.someOtherProperty();
});
Now you can use the enable binding like so:
<input type="button" value="Save Me!" data-bind="enable: canSave" />
Here's a fiddle to demonstrate. Notice how the save button is grayed out until both text boxes have some value.
You can make the logic in your computed as complicated as you need and knockout will keep track of the dependencies and reevaluate it whenever one of the dependent observables changes. This keeps the VM logic from cluttering up your view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With