Search code examples
javascriptyui

YUI setStyle doesn't work


I have the following snippet:

YUI().use('event', function (Y) {
    var button = Y.one("#ckbox");
    button.ancestor(".control-group").next(".control-group").setStyle("display", "none");
    button.on("change", function (e) {
        var checkbox = e.target;    
        if(checkbox.get('checked')) {
            alert("it is checked");
            checkbox.ancestor(".control-group").next(".control-group").setStyle("display", "block");
        } else {
            checkbox.ancestor(".control-group").next(".control-group").setStyle("display", "none");
        }           
    });
});
<script src="http://yui.yahooapis.com/3.4.1pr1/build/yui/yui-min.js"></script>
<div class="control-group form-inline"> 
    <label class="checkbox" for="ckbox"> 
        <input id="ckbox-hiden" name="ckbox-hiden" type="hidden" value="true" /> 
        <input class="field checkbox-checked" id="ckbox" name="ckbox" type="checkbox" value="true" />         
            Show div
    </label> 
</div>
<div class="control-group"> 
    <p>HIDE THIS</p>
</div>

jsFiddle

I want to hide a div and when the checkbox is checked I want to show the div.
I get this error:

TypeError: button.ancestor(...).next(...).setStyle is not a function

Solution

  • You need to add the node module to take advantage of methods which manipulate nodes:

    YUI().use('event', 'node' function (Y) { // ...
    

    YUI().use('event', 'node', function (Y) {
        var button = Y.one("#ckbox");
        button.ancestor(".control-group").next(".control-group").setStyle("display", "none");
        button.on("change", function (e) {
            var checkbox = e.target;    
            if(checkbox.get('checked')) {
                alert("it is checked");
                checkbox.ancestor(".control-group").next(".control-group").setStyle("display", "block");
            } else {
                checkbox.ancestor(".control-group").next(".control-group").setStyle("display", "none");
            }           
        });
    });
    <script src="https://cdn.rawgit.com/stiemannkj1/0214fdc4cccaa77d6e504320cf70a571/raw/63d260364730fb067f103c00862c7e65685256df/yui-3.18.1_build_yui_yui-min.js"></script>
    <div class="control-group form-inline"> 
        <label class="checkbox" for="ckbox"> 
            <input id="ckbox-hiden" name="ckbox-hiden" type="hidden" value="true" /> 
            <input class="field checkbox-checked" id="ckbox" name="ckbox" type="checkbox" value="true" />         
                Show div
        </label> 
    </div>
    <div class="control-group"> 
        <p>HIDE THIS</p>
    </div>