A simple thing I am trying to workout with KnockoutJS.
I have two dropdowns
and a textbox
.
What I need
If both the dropdowns are selected, then only I should get the checkbox displayed. Otherwise, the text input should not visible.
What I tried:
Here is my fiddle: https://jsfiddle.net/vikash208/z4x5meua/13/
I used something like this:
data-bind="visible: selectedValue && selectedControl"
From the above, the conditions are verified as below:
IF selectedValue IS TRUE AND selectedControl IS NOT UNDEFINED
Kindly provide me a solution and also where I went wrong with it. I am a beginner of knockoutJS
Activating Knockout But since the browser doesn't know what it means, you need to activate Knockout to make it take effect. To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel);
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
When the parameter transforms into true-like value (such as boolean true,or nonnull object or array ), the binding removes yourElement. style. display value, making it visible. If this is an observable property, then the binding will update visibility every time the property changes.
When you use multiple conditions in a binding, you need to unwrap the observables so the entire expression can be evaluated.
To do this, just add brackets after the observable:
<input type="text" class="form-control" data-bind="visible: selectedValue() && selectedControl()" />
JSFiddle
You could also create another computed observable with your condition in it (note, you still unwrap the observables in the computed observable). This is probably the better option since it keeps the logic in your view model and can be reused.
Txt.showCondition = ko.computed(function() {
return this.selectedItem() && this.selectedValue()
}, this);
Then just bind the input to this instead:
<input type="text" class="form-control" data-bind="visible: showCondition" />
JSFiddle
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