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?
I have a map object I am placing in a Spring ModelAndView in my
Share
For actually modifying the options, you don’t really need jQuery. You can clear the old options by assigning to the
lengthproperty of theoptionsproperty of theSELECTbox, and then add new options via#addandnew 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
optionson the resulting object):JSON:
JavaScript:
Live example
Directly from an object:
If you’re using the object’s property names as
optionvalues, and the property values as the option text:JSON:
JavaScript:
Live Example
Update: Rather than
you can also do:
Live example
…which I think actually I would tend to use over the
addmethod on theoptionsarray-like-thing (I’m not calling it an array because it has a method,add, that arrays don’t have; and because if you usepush, which arrays do have, it doesn’t work).I’ve tested both methods on
…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.