15

I have a map object I am placing in a Spring ModelAndView in my controller and forwarding to my jsp view to populate a select. After it populates the first time, I want to replace the map object used to populate the select with a json object I am retrieving using jquery AJAX and converting to an object using jQuery.parseJSON. Can I dynamically replace the entire contents of the select with the contents of the json object?

coder
  • 6,111
  • 19
  • 54
  • 73

2 Answers2

27

For actually modifying the options, you don't really need jQuery. You can clear the old options by assigning to the length property of the options property of the SELECT box, and then add new options via #add and new Option().

Here are a couple of examples using jQuery for the XHR part and then doing the options directly:

From an array:

If you're drawing the data from an array within the object (in this case, an array identified by the property options on the resulting object):

JSON:

{
  "options": [
    {"value": "New1", "text": "New Option 1"},
    {"value": "New2", "text": "New Option 2"},
    {"value": "New3", "text": "New Option 3"}
  ]
}

JavaScript:

$.ajax({
  url: "http://jsbin.com/apici3",
  dataType: "json",
  success: function(data) {
    var options, index, select, option;

    // Get the raw DOM object for the select box
    select = document.getElementById('theSelect');

    // Clear the old options
    select.options.length = 0;

    // Load the new options
    options = data.options; // Or whatever source information you're working with
    for (index = 0; index < options.length; ++index) {
      option = options[index];
      select.options.add(new Option(option.text, option.value));
    }
  }
});

Live example

Directly from an object:

If you're using the object's property names as option values, and the property values as the option text:

JSON:

{
  "new1": "New Option 1",
  "new2": "New Option 2",
  "new3": "New Option 3"
}

JavaScript:

$.ajax({
  url: "http://jsbin.com/apici3/2",
  dataType: "json",
  success: function(data) {
    var name, select, option;

    // Get the raw DOM object for the select box
    select = document.getElementById('theSelect');

    // Clear the old options
    select.options.length = 0;

    // Load the new options
    for (name in data) {
      if (data.hasOwnProperty(name)) {
        select.options.add(new Option(data[name], name));
      }
    }
  }
});

Live Example


Update: Rather than

select.options.add(new Option(...));

you can also do:

select.options[select.options.length] = new Option(...);

Live example

...which I think actually I would tend to use over the add method on the options array-like-thing (I'm not calling it an array because it has a method, add, that arrays don't have; and because if you use push, which arrays do have, it doesn't work).

I've tested both methods on

  • IE6,7,8 (Windows)
  • Chrome (Linux & Windows)
  • Firefox (Linux & Windows)
  • Opera (Linux & Windows)
  • Safari (Windows)

...and the both work. Perhaps someone with a Mac could try Safari on OS X for me.

I'd say both ways are very, very well supported.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • should be select.add(new Option(data[name], name)); – Ritesh Feb 17 '11 at 12:46
  • if(document.all){ /*IE*/ select.add(new Option(data[name], name)); }else{ select.appendChild(new Option(data[name], name)); } – Ritesh Feb 17 '11 at 12:47
  • @Ritesh: Not sure I'm following you...? My example works, without branching, on all major browsers (including IE6). – T.J. Crowder Feb 17 '11 at 12:57
  • @T.J. Crowder The 'add' method is available on Select object. options property is an array. There is some cross browser issue for 'add' vs. 'appendChild'. See http://stackoverflow.com/questions/3611615/are-add-and-appendchild-the-same-for-select-dom-objects – Ritesh Feb 17 '11 at 13:11
  • 1
    @Ritesh: Actually, the `options` property isn't (just) an array, it has an `add` method (see my code) that works (again) in all major browsers. (Note that I'm using `add` on the `options`, not on the select element itself.) You're quite right that `appendChild` does *not* work reliably, which is why I'm not using it. Tim's method of adding via `select.options[select.options.length] = new Option(...);` *also* works on every major browser. – T.J. Crowder Feb 17 '11 at 13:58
  • @Ritesh: And when I say "every major browser," I mean it; I've updated the answer with a list. – T.J. Crowder Feb 17 '11 at 14:06
  • @T.J. Crowder Thanks for clarifying it. I agree with you. – Ritesh Feb 18 '11 at 16:55
  • @Ritesh: :-) Thanks for linking to that other question and reminding me of the `options[options.length] = ...` way of doing it. – T.J. Crowder Feb 18 '11 at 17:46
0
       $.ajax({
                type: 'POST',
                url: getpolicytypeUrl ,
                data: { sirket: companyname },
                success: function (data) {

                    $.each(data, function(index, element) {
                        $('#policyshortname').append($('<option>', {
                            text: element.policyShortname
                        }));
                        $('#policyshortname').show(300);
                    });

                }
            });


        $('#policyshortname').html('refresh',true);
Taner Deliloglu
  • 55
  • 1
  • 1
  • 6