How to populate current dropdown with jquery onclick?

I know that there are many solutions for dropdown lists, but I'm trying to create something a little different than usual.

Menu before pressing a button:

<select> <option>Choose Something</option> </select> 

Menu after user click:

 <select> <option>Loading options</option> </select> 

Menu after settings downloaded from the server:

 <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> 

The problem is that after filling the menu, its size is small, and other elements are not displayed until the second click.

Is there any solution with this?

+4
source share
2 answers

Here are some ways to solve the problem. I can help you.

HTML (empty option as place holders)

 <select> <option>Select Something</option> <option>&nbsp;</option> <option>&nbsp;</option> <option>&nbsp;</option> </select> 

Javascript

 var clickCount = 0; $("select").click(function(e) { if (clickCount == 0) $("select").empty().html("<option>Loading options</option>"); clickCount++; if (clickCount == 1) { $("select").click(); return; } if (clickCount == 2) { $("select").empty().html("<option>Select Something</option><option>1</option> <option>2</option> <option>3</option><option>4</option> "); $("select :nth-child(1)").attr("selected", "selected"); } });​ 

Demo 1 or Demo 2 at jsfiddle.net.

Hope this works for you.

+1
source
 $("select").click(function(){ $("select").empty().append("<option>Loading options</option>"); $.ajax({ url: 'http://www.your_server.com/your_page', success: function (data) { $("select").empty().append(data); //your data being: <option>1</option> <option>2</option> <option>3</option><option>4</option> } }) }) 
0
source

Source: https://habr.com/ru/post/1397382/


All Articles