Advertisement
englishextra

load all options of a select with jquery

Mar 17th, 2012
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //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):
  2.  
  3. //JSON:
  4.  
  5. {
  6.   "optionsValues": [
  7.     {"value": "New1", "text": "New Option 1"},
  8.     {"value": "New2", "text": "New Option 2"},
  9.     {"value": "New3", "text": "New Option 3"}
  10.   ]
  11. }
  12.  
  13. //JavaScript:
  14.  
  15. $.ajax({
  16.   url: "http://jsbin.com/apici3",
  17.   dataType: "json",
  18.   success: function(data) {
  19.     var options, index, select, option;
  20.  
  21.     // Get the raw DOM object for the select box
  22.     select = document.getElementById('theSelect');
  23.  
  24.     // Clear the old options
  25.     select.options.length = 0;
  26.  
  27.     // Load the new options
  28.     options = data.optionsValues; // Or whatever source information you're working with
  29.     for (index = 0; index < options.length; ++index) {
  30.       option = options[index];
  31.       select.options.add(new Option(option.text, option.value));
  32.     }
  33.   }
  34. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement