Nitin Aggarwal
Nitin Aggarwal

Reputation: 215

Prevent dropdown until all options are completely added jQuery

I am adding options to my dropdown dynamically on click event. My problem is the dropdown drops before even all options are finished adding and user can see the appending of options.

My Code is something like below.

$(document).on('click', '.someDropdown', function(e) {
   $(this).append('<option class="someClass" value="foo">Foo</option>');
});

How can I make sure the dropdown drops after all the options are finished adding?

Upvotes: 1

Views: 65

Answers (3)

Taytorious
Taytorious

Reputation: 324

I'm assuming your dropdown is JS controlled, and you actually have two click handlers for your dropdown: one to show the dropdown and one to append the options. This is creating a race condition. If you control your dropdown through css, you can eliminate the race condition and append the options before your dropdown shows.

$(document).on('click', '.someDropdown', function(e) {
   $(this).append('<option class="someClass" value="foo">Foo</option>');
   $(this).addClass('enabled');
});

Upvotes: 0

ZhiLI
ZhiLI

Reputation: 209

you can hide your someDropdown before appending and show it after the appending

Upvotes: 0

J.C. Fong
J.C. Fong

Reputation: 546

$(document).on('mousedown', '.someDropdown', function(e) {
   $(this).append('<option class="someClass" value="foo">Foo</option>');
});

The mousedown event occurs when the left mouse button is pressed down over the selected element.

The mousedown() method triggers the mousedown event, or attaches a function to run when a mousedown event occurs.

Upvotes: 3

Related Questions