What's the easiest way to add an option
to a dropdown using jQuery?
Will this work?
$("#mySelect").append('<option value=1>My option</option>');
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.
jQuery addClass() MethodThe addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute.
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”).
Personally, I prefer this syntax for appending options:
$('#mySelect').append($('<option>', { value: 1, text: 'My option' }));
If you're adding options from a collection of items, you can do the following:
$.each(items, function (i, item) { $('#mySelect').append($('<option>', { value: item.value, text : item.text })); });
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