John Beasley
John Beasley

Reputation: 3073

Refresh dropdown selection without page refresh in jQuery

It sounds so simple.

I have this function that runs when the page is loaded:

 function initializeSelect($select, uri, adapt){        
   $.getJSON( uri, function( data ) {
   $select.empty().append($('<option>'));       
   $.each(data, function(index, item) {
     var model = adapt(item);
     var $option = $('<option>');
     $option.get(0).selected = model.selected;
     $option.attr('value', model.value)
       .text(model.text)
       .appendTo($select);      
     });
   });
 });

Which is called here and generates OPTIONS for a dropdown selection:

 initializeSelect($('#commoditySelect'), 'api/sel_keyCommodities.php', function (item) { 
   return {
     value: item.KEY_COMMODITY,
     text: item.KEY_COMMODITY
   }
 });

I need to be able to refresh the dropdown selections without refreshing the page when a modal window closes:

 $('#messageModal').on('hidden.bs.modal', function()
 {
    // I tried this to no avail
    initializeSelect();       
 });

So that way, the dropdown selection will rerun with possibly a new selection that may or may not have been added.

Can this be done, and if so, how?

Upvotes: 0

Views: 2864

Answers (1)

Andreas
Andreas

Reputation: 21881

You could store the values for uri and adapt "in" the <select> with data(...) and use these when calling initializeSelect without parameters (or at least without uri and adapt)

function initializeSelect($select, uri, adapt) {
  if (typeof uri !== "string") {
    uri = select.data("uri");
    adapt = select.data("adapt");
  } else {
    select.data({
      "uri": uri,
      "adapt": adapt
    });
  }

  $.getJSON(uri, function(data) {
    $select.empty().append("<option>");

    $.each(data, function(index, item) {
      var model = adapt(item);

      $("<option>")
        .val(model.value)
        .text(model.text)
        .prop("selected", model.selected)
        .appendTo($select);
    });
  });
}

To "refresh" a <select> you will have to call initializeSelect() passing it the desired <select>

initializeSelect($("commoditySelect"));

An example on jsfiddle

Upvotes: 1

Related Questions