sorold
sorold

Reputation: 533

Bootstrap dropdown with jquery

I have a form, and I'm trying to use a dropdown as a message displayer. When I focus out the input, the dropdown displays. The problem is that it closes right after showing.

<form method="post">
    <input id="name" type="text" name="name">
    <li class="dropdown list-unstyled">
        <a class="dropdown-toggle" role="button"data-toggle="dropdown"></a>
        <ul class="dropdown-menu">
            My message.
        </ul>
    </li>
</form>

Jquery

$(document).ready(function (){
    $('#name').focusout(function () {
       $('.dropdown-toggle').dropdown('toggle');
    });
});

I couldn't figure out why it closes yet. Strange thing is that if I click outside and drag the mouse just a little before releasing it, the dropdown doesn't close. Thanks!

fiddle https://jsfiddle.net/syp7ynqm/

edit: the problem seems to be that the dropdown detects the outside click right after it shows, so it closes (as it should) but I would like to disable this function, only for this first click, so that on the focus out the message would be displayed correctly.

Upvotes: 1

Views: 7391

Answers (4)

saikumar
saikumar

Reputation: 1051

$(document).ready(function (){
    $('#name').focusout(function () {
       $('.dropdown-menu').toggle();
    });
    $(document).mousedown(function(){
    	$('.dropdown-menu').hide();
    })
    
});

Upvotes: 1

Steve K
Steve K

Reputation: 9045

You can just go with the show method. Fiddle.

$(document).ready(function (){
    $('#name').focusout(function () {
       $('.dropdown-menu').show();
    });
});

And your html should look like the following because li should be a child of ul so you would want to go with the folling html.

<form method="post">
    <input id="name" type="text" name="name">
    <div class="dropdown">
        <div class="dropdown-menu">
            My message.
         </div>
     </div>
</form>

Upvotes: 2

Leonardo
Leonardo

Reputation: 314

$(document).ready(function (){

    var $dropDownMenu = $('.dropdown-menu');
    // displays as default
    $dropDownMenu.css("display", "block");

    $('#name')
    .focusin(function () {
       $dropDownMenu.css("display", "none");
    })
    .focusout(function () {
         $dropDownMenu.css("display", "block");
    });
});

Upvotes: 0

stark
stark

Reputation: 2256

Instead of the dropdown method use toggle to show or hide the dropdown.

$(document).ready(function (){
 $('#name').focusin(function(){
            $('.dropdown-menu').toggle();
 });
 $('#name').focusout(function(){
            $('.dropdown-menu').toggle();
 });
});

This results in the dropdown showing up when the input is focused and disappearing when you click away.

Check this fiddle : https://jsfiddle.net/e59xb38p/40/

Upvotes: 0

Related Questions