Close a SELECT dropdown list programmatically with Javascript/jQuery
Asked Answered
O

11

33

I have a dropdown that is initialized with one single value. When the user clicks it, the single element is removed and a new element is added saying "Loading", then an AJAX call is issued to the server and when returns, the new values are added to the control.

The problem is that the control remains open while updating, and I would like to close it.

This is an example: http://jsfiddle.net/vtortola/CGuBk/2/

The example's AJAX does not get data probably because something wrong I am doing when calling the jsfiddle api, but it shows how the SELECT remains open during update.

I want to know how to close the dropdown list programmatically w/o focus in another input.

Ola answered 1/6, 2012 at 14:12 Comment(0)
R
14

I'm not sure about anyone else, but I'm using the latest stable build of Chrome, and none of the other answers involving .blur() work for me.

This question asks the inverse: Programmatically open a drop-down menu

The conclusion that seemed to be obtained is that it's not possible due to the way the browser handles field element clicks.

A better solution would be to replace the dropdown with a pure HTML one and hide it when needed with a simple .hide() command.

Rubrician answered 1/6, 2012 at 14:22 Comment(1)
when changing a textbox, i open a "prompt" box. If the change occurs when clicking the select, i avoid now the disturbing dropdown-list by hiding the selects before and showing again after the prompt. visibleselects = $('select:visible').hide(); ... visibleselects.show();Fillet
U
12

Just add this line end of your close within click.

$(this).blur();  

So it will look like

$select.click(function(e){

    $select.html('<option value="-1">Loading</option>');

    $(this).blur();
    ......
    ...
});

DEMO

HAH ! If we have an issue with Chrome new version then:

Take a fake select like following:

<select class="fake" style="display: none">
    <option value="-1">Loading</option>
</select>

and do something like:

$select.click(function(e) {
    $(this).hide(0); // hide current select box

    //$select.html('<option value="-1">Loading</option>');

    $('select.fake').show(0); // show the fake slide

    $.ajax({
           // your code
        }).done(function(data) {

           $('select.fake').hide(0);
           $select.show(0);

        })
        ......
    }):

DEMO

Ushijima answered 1/6, 2012 at 14:15 Comment(4)
+1 first to answer, and with a demo!Sigismund
If the intention is to close the dropdown list, then this doesn't work in Chrome 19 (the latest one), and so shouldn't be relied upon.Rubrician
so there is no way in the latest chrome ? :(Ola
@Ola As of nowadays this answer is the correct one.Billhook
O
7

After...

$select.html('<option value="-1">Loading</option>');

Try adding...

$select.blur();
Odds answered 1/6, 2012 at 14:15 Comment(0)
T
5

I think all you need to do is target something else or should I say lose focus on the select (blur it)

<select>
    <option value="0">Initial Value</option>
</select>

var $select = $('select');
$select.click(function(e){

    $select.html('<option value="-1">Loading</option>');

    $.ajax({
        url: '/echo/json/',
        method:'post',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: { json: JSON.stringify([1, 2, 3]), delay:1 }
    }).done(function(data){

        $.each($.map(data, function (item, i) {
                    return "<option value='" + item +"' >" + item + "</option>";

                }), function (i, item) {
                    $element.append(item);
                });

    }).fail(function(){
        alert('error');
    });

   e.preventDefault();
   e.stopPropagation(); 
   $(this).blur();    
});
Thaumatrope answered 1/6, 2012 at 14:15 Comment(0)
M
3

I know this is an old question and already have an answer but I think the following solution can be a fair way to achieve the goal.

You can simulate the closure of the select by re-rendering it. In jQuery you can implement a simple plugin to achieve that:

$.fn.closeSelect = function() {
    if($(this).is("select")){
        var fakeSelect = $(this).clone();
        $(this).replaceWith(fakeSelect);
    }
};

and use it this way:

$("#mySelect").closeSelect();
Mensch answered 11/11, 2013 at 10:41 Comment(1)
Fantastic! I especially like this solution because it doesn't use a timer.Martine
O
1

SOLUTION 1 I found very easy solution.

select.style.display = "none";
setTimeout(function () {
    select.style.display = "block";
}, 10);

This hide element in DOM, this cause that dropdown will be closed and then with 10ms delay (without delay it does not work) return it into DOM.

SOLUTION 2: Little bit more complicated but without delay is totaly remove element from DOM and then immediately return it back.

var parent = select.parentElement;
var anchor = document.createElement("div");
parent.insertBefore(anchor, select);
parent.removeChild(select);
parent.insertBefore(select, anchor);
parent.removeChild(anchor);

This stores parrent of element, then bring anchor before select. Anchor is there for restoring select in the same position in DOM then before. Of course it can be implemented to function select element.

HTMLSelectElement.prototype.closeDropdown = function () {
    var parent = this.parentElement;
    var anchor = document.createElement("div");
    parent.insertBefore(anchor, this);
    parent.removeChild(this);
    parent.insertBefore(this, anchor);
    parent.removeChild(anchor);
}

and then just call

select.closeDropdown();

Example

Opal answered 8/5, 2016 at 18:2 Comment(0)
G
0
$('.select').on('change', function () {
    $(this).click();
});
Grace answered 13/6, 2015 at 7:41 Comment(0)
B
0

Old post I know but I have a very simple solution.

$(someSelectElement).on('change', function(e) {
    e.target.size = 0    
}

That will collapse the select element if you click on any item in the list.

Burlingame answered 16/7, 2015 at 15:59 Comment(0)
W
0

In case anyone else out there is using Angular2, the solution that worked there for me was to add a (focus) event that calls $($event.srcElement).attr("disabled","disabled");

I then add a timeout to re-enable the element when I want it to become active again.

Wolford answered 18/1, 2016 at 23:46 Comment(0)
O
0

The easiest way I found to close a selected element is to disable it temporarily:

$selectElement.attr('disabled', true);

setTimeout(() => {
   $selectElement.attr('disabled', false);
}, 4);
Orvie answered 19/1, 2019 at 17:10 Comment(0)
A
0

Please try this one, work for me:

$("#mySelect").dropdown('toggle');
Abran answered 5/2, 2022 at 0:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.