Add or Append or Insert Options to Select Options by using jQuery or JavaScript |
X

Congrats, You are Subscribed to Receive Updates.

Add or Append or Insert Options to Select Options by using jQuery or JavaScript


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' }));

 add-or-append-or-insert-options-to-select-options-by-using-jquery-or-javascript

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.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, PHP and Data Analyst. Database Management Advance Level

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar