Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS data-bind="Visible :" with two conditions is not working

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

like image 937
Vikash Avatar asked Nov 01 '16 07:11

Vikash


People also ask

How do you activate a KnockoutJS model?

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);

What is $data in Knockout?

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.

What happens in visible binding?

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.


1 Answers

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

like image 109
Steve Avatar answered Oct 21 '22 20:10

Steve