Thursday, 3 February 2011

Showing / hiding field depending on another field

I needed this kind of functionality:
I decide to use jQuery for this functionality. Here's how it's done:

1) jQuery was added to styles library through module

2) in my custom form in "AdditionalPageHead" following was added:
<script src="/Style Library/Scripts/jquery-1.5.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("nobr:contains('Cel ')").append('<span title="This field is required" class="ms-formvalidation">*</span>');
            HideFields();
            AddEvent();
        });
        function HideFields() {
            $("nobr:contains('Cel ')").closest('tr').hide();
        }

        function getQueryString() {
            var assoc = new Array();
            var queryString = unescape(location.search.substring(1));
            var keyValues = queryString.split('&');
            for (var i in keyValues) {
                var key = keyValues[i].split('=');
                assoc[key[0]] = key[1];
            }
            return assoc;
        }

        function AddEvent() {
            var tmp = $("nobr:contains('Typ ')").closest('td').next().children('span:first').children('select').each(function () {
                var type = this.type;
                var tag = this.tagName.toLowerCase();
                if (tag == 'select') {
                    $(this).change(function () {
                        $("nobr:contains('Cel ')").closest('tr').toggle();
                    });
                }
                var fieldsetName = $(this).val();
                if (fieldsetName != 'Prywatne') {
                    $("nobr:contains('Cel ')").closest('tr').show();
                }
            });
        }
    </script>

Basically I'm getting things done in three steps:
1) add an asteriks mark to mark field as required (although I'm validating this through code)
2) hide field "Cel (tylko dla służbowych)"
3) if different option was selected inside "select" - show or hide hidden field

No comments:

Post a Comment