Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create options of a select element dynamically using jquery?

Tags:

I need to create options of a select element dynamically via an ajax call. The number of options and their content will vary. This is how it looks prior to the ajax call:

 <select name="groupid" style="width:100%;"> <option value="0" selected>(Please select an option)</option> </select> 

Here is one of my attempts to create an option element with a dummy value:

$("<option></option>", {value: "999"}).appendTo('.select-group'); 

But it adds it outside of select. I also don't know how to set the text within .

Any ideas? I've seen some questions about populating existing select forms with a static number of existing options but not one like this.

Thanks.

like image 505
David Willis Avatar asked Mar 15 '12 20:03

David Willis


People also ask

How do I add dynamic options to select?

To dynamically add options to an existing select in JavaScript, we can use a new Option object append it to the select element with the options. add method. to add a select element. to select the select element with document.

How do you select a particular option in a select element in jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).


1 Answers

Where's .select-group? If you use id of #groupid then this should work just fine...

$('<option>').val('999').text('999').appendTo('#groupid'); 
like image 169
elclanrs Avatar answered Oct 13 '22 03:10

elclanrs