cancel
Showing results for 
Search instead for 
Did you mean: 

Show and hide an input field based on checkbox with ko bindings

Show and hide an input field based on checkbox with ko bindings

I have an input that I want to show and hide based on a checkbox toggle.

Based on the KOjs docs, and what I know about kojs in Magento 2, I tried this, but it's not working.
Shouldn't the div be toggling based on the status of "otherChecked"?

Thanks

```

<input class="sf-other-checkbox" type="checkbox" id="other" data-bind="checked: otherChecked">
<label style="margin-bottom: 0.5rem;" for="other">Other</label>

<div class="field sf-other-input required" data-bind="visible: otherChecked">
<label for="input-for-other" class="label">Other</label>
<div class="control">
<input type="text" name="input_for_other" id="input-for-other" title="<?php /* @escapeNotVerified */
echo __('Other') ?>" class="input-text" data-validate="{required:true}">
</div>
</div>
 

```

and 

```

define(['jquery', 'uiComponent'], function ($, Component) {
'use strict'

return Component.extend({
defaults: {
shoppingType: '',
otherChecked: false
},

initObservable: function () {
this._super().observe(['shoppingType', 'otherChecked']);

return this;
} })
}); 

 

2 REPLIES 2

Re: Show and hide an input field based on checkbox with ko bindings

Hi @web_master12,

 

Can you try replacing your JS code with below code. Try to replace the values according to your html file.

https://magento.stackexchange.com/questions/216585/magento2-checkbox-change-function-in-knockout-js/...

return Component.extend({        defaults: {
            template: 'Namespace_Mymodule/custom'
        },        initObservable: function () {

            this._super()
                .observe({
                    CheckVal: ko.observable(false)                        
                });

            this.CheckVal.subscribe(function (newValue) {
                if(newValue){                    console.log('checked');
                }else{                    console.log('Unchecked');
                }
            });

            return this;
        }
    });

Hope this helps you!

Problem Solved! Click Kudos & Accept as Solution! 

Re: Show and hide an input field based on checkbox with ko bindings

I found the issue. I had a display: none on my div, so it was working just fine, but I couldn't see it, and it didn't have any errors...