Add/Remove options from a Select box with jQuery

6 Flares Twitter 3 Facebook 2 Google+ 1 Pin It Share 0 LinkedIn 0 Filament.io 6 Flares ×

Ever wanted to refresh your options in a drop down without having to refresh the screen? Here we will look at how to add and remove options from a select box using jQuery without refreshing the page.

Adding a single option via .append

A single option can be added by appending HTML to the select box. See example:

$('#optExample').append('<option value="newVal">Option Text</option>');

This added option will be the selected option; to change this remove the selected=”selected”.

Adding a single option via Javascript only

Add a single option using the newOption function. See example:

var options =  $('#optExample').attr('options');
options[options.length] = newOption('Option Text', 'newVal', true, true);

The true, true properties select the option upon creation. Remove them if you do not want the option selected when added.

Adding multiple options

Use the following to replace an existing set of options with a new set. The array could be created anyway you wish, however since we want the page to keep from refreshing either populate the list upon page load or via AJAX. We’ll use the following:

var dataArr = [{'value':'val1','text':'text1'},
               {'value':'val2','text':'text2'},
               {'value':'val3','text':'text3'},
               {'value':'val4','text':'text4'},
               {'value':'val5','text':'text5'},
               {'value':'val6','text':'text6'},
               {'value':'val7','text':'text7'}];

// Removes all options for the select box
$('#optExample option').remove();

// .each loops through the array
$.each(dataArr, function(i){
    $('#optExample').append($("<option></option>")
                    .attr("value",dataArr[i]['value'])
                    .text(dataArr[i]['text']));
});

Adding multiple options by criteria

If you want to take an array of data and populate the select box only when the criteria is met the code is similar in nature. See example:

var dataArr = [{'key':'1','value':'val1','text':'text1'},
               {'key':'1','value':'val2','text':'text2'},
               {'key':'2','value':'val3','text':'text3'},
               {'key':'2','value':'val4','text':'text4'},
               {'key':'2','value':'val5','text':'text5'},
               {'key':'3','value':'val6','text':'text6'},
               {'key':'3','value':'val7','text':'text7'}];
// Removes all options for the select box
$('#optExample option').remove();

// .each loops through the array
$.each(dataArr, function(i){
    //only append options with a "key" value of 2
    if (dataArr[i]['key'] == '2'){
        $('#optExample').append($("<option></option>")
                        .attr("value",dataArr[i]['value'])
                        .text(dataArr[i]['text']));
    }
});

A common use for something like this is where an option list is populated when another form option is selected. Based upon your page design rather than execute an AJAX call you could populate the entire array with all the options on page load. This would increase initial page weight but reduce I/O later on.

There are possibly more jQuery plugins that complete similar functionality but this is all possible with native jQuery.

Comments

  1. Hi ..I’m trying to add the options dynamically for jquery mobile, i’m not able to use the below code….some times the select box is loosing its CSS styles also…Can any body give reply to this post.

    var dataArr = [{‘value’:’val1′,’text’:’text1′},
    {‘value’:’val2′,’text’:’text2′},
    {‘value’:’val3′,’text’:’text3′},
    {‘value’:’val4′,’text’:’text4′},
    {‘value’:’val5′,’text’:’text5′},
    {‘value’:’val6′,’text’:’text6′},
    {‘value’:’val7′,’text’:’text7′}];

    // Removes all options for the select box
    $(‘#optExample option’).remove();

    // .each loops through the array
    $.each(dataArr, function(i){
    $(‘#optExample’).append($(“”)
    .attr(“value”,dataArr[i][‘value’])
    .text(dataArr[i][‘text’]));
    });

  2. CreativeCG says:

    I personally have not tried this in jQuery Mobile yet, nor do I even know of it. Perhaps someone may be able to offer more insight to this.

  3. Hi Team,

    Pls find the code which i wrote and correct me any thng wrong in my code..

    $(document).ready(function(){

    $(“#select1”).change(function(){
    $.getJSON(“/CG_Mobile/json?”,{pid: $(this).val(), ajax: “true”}, function(j){
    $(“#kishore option”).remove();
    var array=j.Messages;
    alert(array);
    $.each(array, function(i){
    //alert(i);
    $(“#kishore”).append(”+array[i].option+”);

    //alert(”+array[i].option+”);

    }).change();
    });
    });

    });

    Data Source

    Campaign Type

    Select Campaign Type

    Campaign RunID

    Select Campaign RunID

     

    In the above code for the id=”kishore”, i need to populate data on change of select1 id.
    The values are getting perfect and data is diplaying properly ,but on select the option the text is not displaying on page.

  4. sorry the tags are not displaying here…

  5. Thank you guys….the problem is because of bug in the Jquery version.Now i’m using version of jquery mobile(jquery.mobile-1.2.0.min.js)…

Speak Your Mind

*

6 Flares Twitter 3 Facebook 2 Google+ 1 Pin It Share 0 LinkedIn 0 Filament.io 6 Flares ×