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.
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.
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”).
Where's .select-group
? If you use id of #groupid
then this should work just fine...
$('<option>').val('999').text('999').appendTo('#groupid');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With