Izzy
Izzy

Reputation: 6866

show and hide div based on information

I'm developing a web app using C# MVC. One of page has several divs which should be hidden when the page loads unless they contain information which is pulled from the database. Users have a drop down which they choose from and on selected the appropriate div shows. Currently I'm achieving this using jQuery as:

function showDiv() {
   var divID = $("#usersddl option:selected").val();
   $("#" + divID).show();
   $("#" + divID).siblings().hide();
}

Currently the function is called onchange of usersddl.

Each dropdown option is saved in the database along with it's information which is provided by the user in the div if it currently doesn't have any info. I can't seem to figure out how to always show the div if it contains information otherwise show it on dropdown selected.

Upvotes: 0

Views: 164

Answers (1)

Denys Wessels
Denys Wessels

Reputation: 17049

You could write a litle bit of jQuery to loop through all the divs on your page and check the values of the input fields in every div.If the div contains only empty inputs then hide it, otherwise show it.

<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('.infoDiv').each(function (i, obj) {

                var textboxes = $(this).find("input[type=text]");

                var containsInfo = false;

                for(var i = 0; i < textboxes.length;i++)
                {
                    var text = $(textboxes[0]).val();
                    if (text != "")
                        containsInfo = true;
                }

                if (!containsInfo)
                    $(this).hide();

            });

        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="infoDiv">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" value="Some name..." /></td>
        </tr>
    </table>
    </div>
        <div class="infoDiv">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" /></td>
        </tr>
    </table>
    </div>
    </form>
</body>

Upvotes: 1

Related Questions