Add or Append or Insert Options to Select Options by using jQuery or JavaScript
- Article
- Comment
Add or Append Options to Select Options by using jQuery or JavaScript. Several tutorials available already for adding options to a select options drop down. Anyhow I am just discussing my way of appending or adding an item of option to the existing select options list.
JQuery
With help of jQuery you can use the following code to add your options dynamically.
Append one option :
If it’s only one option, it’s very simple to do like the below one.
$('#Select-option-id-here').append($('', { value: 7, text: 'Dynamic Append' }));
Append More options :
You might have the options in a array. We can use the `$.each` to append all with it.
var sel_opn = $('#Select-option-id-here'); var items = { 'red' : 'Red', 'blue' : 'Blue', 'green' : 'Green', 'yellow' : 'Yellow' }; $.each(items, function(text, key) { var option = new Option(key, text); sel_opn.append($(option)); });
And it’s a slow method because it iterates every time and it will take more time if your array is big.
Remove all element and adding all new data’s.
$('option', sel_opn).remove();
And than you can add it.
var items = { 'red' : 'Red', 'blue' : 'Blue', 'green' : 'Green', 'yellow' : 'Yellow' }; $.each(items, function(text, key) { var option = new Option(key, text); sel_opn.append($(option)); });
Insert into a position
Inserting an element in a position, not only adding an element at the end. You can insert in a place.
$('#Select-option-id-here'). eq(7).before($('', { value: 7, text: 'Dynamic Append' }));
JavaScript:
This way very simple in JavaScript. It’s easy to work on all the browser’s as well.
var sel_opn = document.getElementById('Select-option-id-here '); sel_opn .options[ sel_opn .options.length]= new Option('Dynamic Append ', '7');
I hope you like this article which discuss with jQuery and JavaScript to append, or insert or adding a new item in the select options list. If you really enjoy this article, please post your comment and subscribe my newsletter and follow me on social sites to receive updates from me.