javascriptjqueryhtmlcsstwitter-bootstrap

Don't hide dropdown list when clicked inside it


I've made this dropdown menu using bootstrap. The problem is that it hides itself when I click inside it or check a checkbox inside it as well. How do I get it not to close unless clicked somewhere outside the dropdown. Thanks in advance!

<div class="ibox-tools">
    <a class="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="true">
        <i class="fa fa-line-chart"></i>
    </a>

    <ul class="dropdown-menu dropdown-user" style="width:200px">
        @foreach(PKG_VLTROUTINE_GET_EXCHAGEINFO_Result cur in Model)
        {
            <li style="padding:5px">
                <strong>@cur.VLTNAME</strong>
                &nbsp;@cur.RATE
                <br />
                <small>@cur.VLTFULLNAME</small>
                <small>
                    (
                    @cur.RATEDIF
                    @if (cur.DIRECTION == 1)
                    {
                        <i style="color:#1ab394" class="fa fa-level-up text-navy"></i>
                    }
                    else
                    {
                        <i style="color:#ed5565" class="fa fa-level-down text-navy"></i>
                    }
                    )
                </small>
                <div class="MsSwitch MsSwitch-update">
                    <input data-evoldvall="-1" value="-1" type="checkbox" checked="" data-valtrue="-1" data-valfalse="" name="@cur.VLTNAME" class="evCheckBox">
                    <label for="@cur.VLTNAME"></label>
                </div>
                <li class="divider" style="margin:0px"></li>
            </li>
        }
    </ul>

Solution

  • Remove the data attribute data-toggle="dropdown" and implement the open/close of the dropdown can do the job. First handle the click on the link to open/close the dropdown like this :

    $('a.dropdown').on('click', function () {
     $(this).parent().toggleClass('open'); 
    });
    

    Then wait for the clicks outside of the dropdown to close it like this :

    $('body').on('click', function (e) {
     if (!$('a.dropdown').is(e.target) && $('a.dropdown').has(e.target).length === 0 && $('.open').has(e.target).length === 0 ) { 
    $('a.dropdown').parent().removeClass('open'); } });