Search code examples
jqueryformsfieldsettoggleclass

Style-able collapsible <fieldset> with jQuery


There is a log-in and registration form in separate fieldset-s like shown below:

<fieldset class="login selected">
    <legend class="login_link">Login</legend>
    <div class="form_container">
        <form id="loginform">
            [loginform]
        </form>
    </div>
</fieldset>
<fieldset class="reg">
    <legend class="registration_link">Registration</legend>
    <div class="form_container clearfix">
        <form id="regform">
            [regform]
       </form>
    </div>
</fieldset>

one is open another is closed by default with css styling

.login .form_container {
    display: block;
}
.reg .form_container {
    display: none;
}
fieldset {
    border: none;
}
.selected {
    border: 1px inset #000;
}
legend {
    background: #ccc;
    cursor: pointer;
}

fieldset-s can be collapsible using jQuery. Adding and removing the .selected class allow to nicely style the open and the closed separately

$(".login_link,.registration_link").live("click",function(){
    $(this).parent().parent().children().children('.form_container').toggle();
    $(this).parent().parent().children().toggleClass("selected");
});

​

see the result: http://jsfiddle.net/eapo/43UUP/11/embedded/result/

Can you make more optimal code to do this?


Solution

  • This is a bit cleaner:

    $(".login_link,.registration_link").on("click",function(){
        $(".form_container").toggle()
                            .closest("fieldset")
                            .toggleClass("selected");
    });
    

    Note: As of jQuery 1.7, .live() is deprecated. Use .on().

    Here's a working fiddle.